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 gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { struct dev_pagemap *pgmap = NULL; int nr_start = *nr, ret = 0; pte_t *ptep, *ptem; ptem = ptep = pte_offset_map(&pmd, addr); do { pte_t pte = gup_get_pte(ptep); struct page *head, *page; /* * Similar to the PMD case below, NUMA hinting must take slow * path using the pte_protnone check. */ if (pte_protnone(pte)) goto pte_unmap; if (!pte_access_permitted(pte, write)) goto pte_unmap; if (pte_devmap(pte)) { pgmap = get_dev_pagemap(pte_pfn(pte), pgmap); if (unlikely(!pgmap)) { undo_dev_pagemap(nr, nr_start, pages); goto pte_unmap; } } else if (pte_special(pte)) goto pte_unmap; VM_BUG_ON(!pfn_valid(pte_pfn(pte))); page = pte_page(pte); head = compound_head(page); if (!page_cache_get_speculative(head)) goto pte_unmap; if (unlikely(pte_val(pte) != pte_val(*ptep))) { put_page(head); goto pte_unmap; } VM_BUG_ON_PAGE(compound_head(page) != head, page); SetPageReferenced(page); pages[*nr] = page; (*nr)++; } while (ptep++, addr += PAGE_SIZE, addr != end); ret = 1; pte_unmap: if (pgmap) put_dev_pagemap(pgmap); pte_unmap(ptem); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoCopyBufferSubData(GLenum readtarget, GLenum writetarget, GLintptr readoffset, GLintptr writeoffset, GLsizeiptr size) { buffer_manager()->ValidateAndDoCopyBufferSubData( &state_, readtarget, writetarget, readoffset, writeoffset, size); } Commit Message: Implement immutable texture base/max level clamping It seems some drivers fail to handle that gracefully, so let's always clamp to be on the safe side. BUG=877874 TEST=test case in the bug, gpu_unittests [email protected] Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: I6d93cb9389ea70525df4604112223604577582a2 Reviewed-on: https://chromium-review.googlesource.com/1194994 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#587264} 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: TIFFReadDirEntryCheckRangeLong8Slong(int32 value) { if (value < 0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary. 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: _zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { zip_cdir_t *cd; zip_uint64_t offset; zip_uint8_t eocd[EOCD64LEN]; zip_uint64_t eocd_offset; zip_uint64_t size, nentry, i, eocdloc_offset; bool free_buffer; zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64; eocdloc_offset = _zip_buffer_offset(buffer); _zip_buffer_get(buffer, 4); /* magic already verified */ num_disks = _zip_buffer_get_16(buffer); eocd_disk = _zip_buffer_get_16(buffer); eocd_offset = _zip_buffer_get_64(buffer); if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return NULL; } if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); return NULL; } if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) { _zip_buffer_set_offset(buffer, eocd_offset - buf_offset); free_buffer = false; } else { if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) { _zip_error_set_from_source(error, src); return NULL; } if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) { return NULL; } free_buffer = true; } if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } size = _zip_buffer_get_64(buffer); if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } _zip_buffer_get(buffer, 4); /* skip version made by/needed */ num_disks64 = _zip_buffer_get_32(buffer); eocd_disk64 = _zip_buffer_get_32(buffer); /* if eocd values are 0xffff, we have to use eocd64 values. otherwise, if the values are not the same, it's inconsistent; in any case, if the value is not 0, we don't support it */ if (num_disks == 0xffff) { num_disks = num_disks64; } if (eocd_disk == 0xffff) { eocd_disk = eocd_disk64; } if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } if (num_disks != 0 || eocd_disk != 0) { zip_error_set(error, ZIP_ER_MULTIDISK, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } nentry = _zip_buffer_get_64(buffer); i = _zip_buffer_get_64(buffer); if (nentry != i) { zip_error_set(error, ZIP_ER_MULTIDISK, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } size = _zip_buffer_get_64(buffer); offset = _zip_buffer_get_64(buffer); if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } if (free_buffer) { _zip_buffer_free(buffer); } if (offset > ZIP_INT64_MAX || offset+size < offset) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return NULL; } if ((flags & ZIP_CHECKCONS) && offset+size != eocd_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); return NULL; } if ((cd=_zip_cdir_new(nentry, error)) == NULL) return NULL; cd->is_zip64 = true; cd->size = size; cd->offset = offset; return cd; } Commit Message: Make eocd checks more consistent between zip and zip64 cases. CWE ID: CWE-119 Target: 1 Example 2: Code: static int tcp_prune_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq); NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) tcp_clamp_window(sk); else if (tcp_under_memory_pressure(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); tcp_collapse_ofo_queue(sk); if (!skb_queue_empty(&sk->sk_receive_queue)) tcp_collapse(sk, &sk->sk_receive_queue, skb_peek(&sk->sk_receive_queue), NULL, tp->copied_seq, tp->rcv_nxt); sk_mem_reclaim(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* Collapsing did not help, destructive actions follow. * This must not ever occur. */ tcp_prune_ofo_queue(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* If we are really being abused, tell the caller to silently * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED); /* Massive buffer overcommit. */ tp->pred_flags = 0; return -1; } Commit Message: tcp: make challenge acks less predictable Yue Cao claims that current host rate limiting of challenge ACKS (RFC 5961) could leak enough information to allow a patient attacker to hijack TCP sessions. He will soon provide details in an academic paper. This patch increases the default limit from 100 to 1000, and adds some randomization so that the attacker can no longer hijack sessions without spending a considerable amount of probes. Based on initial analysis and patch from Linus. Note that we also have per socket rate limiting, so it is tempting to remove the host limit in the future. v2: randomize the count of challenge acks per second, not the period. Fixes: 282f23c6ee34 ("tcp: implement RFC 5961 3.2") Reported-by: Yue Cao <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Cc: Yuchung Cheng <[email protected]> Cc: Neal Cardwell <[email protected]> Acked-by: Neal Cardwell <[email protected]> Acked-by: Yuchung Cheng <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: void HTMLMediaElement::dispose() { closeMediaSource(); clearMediaPlayerAndAudioSourceProviderClientWithoutLocking(); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} 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: make_random_bytes(png_uint_32* seed, void* pv, size_t size) { png_uint_32 u0 = seed[0], u1 = seed[1]; png_bytep bytes = png_voidcast(png_bytep, pv); /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR * bit-20. The top 1 bit is in u1, the bottom 32 are in u0. */ size_t i; for (i=0; i<size; ++i) { /* First generate 8 new bits then shift them in at the end. */ png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff; u1 <<= 8; u1 |= u0 >> 24; u0 <<= 8; u0 |= u; *bytes++ = (png_byte)u; } seed[0] = u0; seed[1] = u1; } 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: bool WorkerThread::isCurrentThread() { return m_started && backingThread().isCurrentThread(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); } Commit Message: Issue 761: Heap overflow reading corrupted 7Zip files The sample file that demonstrated this had multiple 'EmptyStream' attributes. The first one ended up being used to calculate certain statistics, then was overwritten by the second which was incompatible with those statistics. The fix here is to reject any header with multiple EmptyStream attributes. While here, also reject headers with multiple EmptyFile, AntiFile, Name, or Attributes markers. 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 phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */ { phar_zip_dir_end locator; char buf[sizeof(locator) + 65536]; zend_long size; php_uint16 i; phar_archive_data *mydata = NULL; phar_entry_info entry = {0}; char *p = buf, *ext, *actual_alias = NULL; char *metadata = NULL; size = php_stream_tell(fp); if (size > sizeof(locator) + 65536) { /* seek to max comment length + end of central directory record */ size = sizeof(locator) + 65536; if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } } else { php_stream_seek(fp, 0, SEEK_SET); } if (!php_stream_read(fp, buf, size)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) { memcpy((void *)&locator, (void *) p, sizeof(locator)); if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) { /* split archives not handled */ php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname); } return FAILURE; } if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname); } php_stream_close(fp); return FAILURE; } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* read in archive comment, if any */ if (PHAR_GET_16(locator.comment_len)) { metadata = p + sizeof(locator); if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname); } php_stream_close(fp); pefree(mydata, mydata->is_persistent); return FAILURE; } mydata->metadata_len = PHAR_GET_16(locator.comment_len); if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) { mydata->metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent)); } } else { ZVAL_UNDEF(&mydata->metadata); } goto foundit; } } php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname); } return FAILURE; foundit: mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->is_zip = 1; mydata->fname_len = fname_len; ext = strrchr(mydata->fname, '/'); if (ext) { mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext); if (mydata->ext == ext) { mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } /* clean up on big-endian systems */ /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* read in central directory */ zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); entry.phar = mydata; entry.is_zip = 1; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; #define PHAR_ZIP_FAIL_FREE(errmsg, save) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ efree(save); \ return FAILURE; #define PHAR_ZIP_FAIL(errmsg) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ return FAILURE; /* add each central directory item to the manifest */ for (i = 0; i < PHAR_GET_16(locator.count); ++i) { phar_zip_central_dir_file zipentry; zend_off_t beforeus = php_stream_tell(fp); if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) { PHAR_ZIP_FAIL("unable to read central directory entry, truncated"); } /* clean up for bigendian systems */ if (memcmp("PK\1\2", zipentry.signature, 4)) { /* corrupted entry */ PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature"); } if (entry.is_persistent) { entry.manifest_pos = i; } entry.compressed_filesize = PHAR_GET_32(zipentry.compsize); entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize); entry.crc32 = PHAR_GET_32(zipentry.crc32); /* do not PHAR_GET_16 either on the next line */ entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp); entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.header_offset = PHAR_GET_32(zipentry.offset); entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) + PHAR_GET_16(zipentry.extra_len); if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) { PHAR_ZIP_FAIL("Cannot process encrypted zip files"); } if (!PHAR_GET_16(zipentry.filename_len)) { PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)"); } entry.filename_len = PHAR_GET_16(zipentry.filename_len); entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent); if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated"); } entry.filename[entry.filename_len] = '\0'; if (entry.filename[entry.filename_len - 1] == '/') { entry.is_dir = 1; if(entry.filename_len > 1) { entry.filename_len--; } entry.flags |= PHAR_ENT_PERM_DEF_DIR; } else { entry.is_dir = 0; } if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { size_t read; php_stream *sigfile; zend_off_t now; char *sig; now = php_stream_tell(fp); pefree(entry.filename, entry.is_persistent); sigfile = php_stream_fopen_tmpfile(); if (!sigfile) { PHAR_ZIP_FAIL("couldn't open temporary file"); } php_stream_seek(fp, 0, SEEK_SET); /* copy file contents + local headers and zip comment, if any, to be hashed for signature */ php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL); /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* copy central directory header */ php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL); if (metadata) { php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len)); } php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET); sig = (char *) emalloc(entry.uncompressed_filesize); read = php_stream_read(fp, sig, entry.uncompressed_filesize); if (read != entry.uncompressed_filesize) { php_stream_close(sigfile); efree(sig); PHAR_ZIP_FAIL("signature cannot be read"); } mydata->sig_flags = PHAR_GET_32(sig); if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) { efree(sig); if (error) { char *save; php_stream_close(sigfile); spprintf(&save, 4096, "signature cannot be verified: %s", *error); efree(*error); PHAR_ZIP_FAIL_FREE(save, save); } else { php_stream_close(sigfile); PHAR_ZIP_FAIL("signature cannot be verified"); } } php_stream_close(sigfile); efree(sig); /* signature checked out, let's ensure this is the last file in the phar */ if (i != PHAR_GET_16(locator.count) - 1) { PHAR_ZIP_FAIL("entries exist after signature, invalid phar"); } continue; } phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len); if (PHAR_GET_16(zipentry.extra_len)) { zend_off_t loc = php_stream_tell(fp); if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory"); } php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET); } switch (PHAR_GET_16(zipentry.compressed)) { case PHAR_ZIP_COMP_NONE : /* compression flag already set */ break; case PHAR_ZIP_COMP_DEFLATE : entry.flags |= PHAR_ENT_COMPRESSED_GZ; if (!PHAR_G(has_zlib)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("zlib extension is required"); } break; case PHAR_ZIP_COMP_BZIP2 : entry.flags |= PHAR_ENT_COMPRESSED_BZ2; if (!PHAR_G(has_bz2)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("bzip2 extension is required"); } break; case 1 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip"); case 2 : case 3 : case 4 : case 5 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip"); case 6 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip"); case 7 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip"); case 9 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip"); case 10 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip"); case 14 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip"); case 18 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip"); case 19 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip"); case 97 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip"); case 98 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip"); default : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip"); } /* get file metadata */ if (PHAR_GET_16(zipentry.comment_len)) { if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in file comment, truncated"); } p = buf; entry.metadata_len = PHAR_GET_16(zipentry.comment_len); if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) { entry.metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent)); } } else { ZVAL_UNDEF(&entry.metadata); } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { php_stream_filter *filter; zend_off_t saveloc; /* verify local file header */ phar_zip_file_header local; /* archive alias found */ saveloc = php_stream_tell(fp); php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET); if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)"); } /* verify local header */ if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)"); } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry.offset = entry.offset_abs = sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len); php_stream_seek(fp, entry.offset, SEEK_SET); /* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */ fp->writepos = 0; fp->readpos = 0; php_stream_seek(fp, entry.offset, SEEK_SET); fp->writepos = 0; fp->readpos = 0; /* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */ mydata->alias_len = entry.uncompressed_filesize; if (entry.flags & PHAR_ENT_COMPRESSED_GZ) { filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else { { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } } /* return to central directory parsing */ php_stream_seek(fp, saveloc, SEEK_SET); } phar_set_inode(&entry); zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info)); } mydata->fp = fp; if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { mydata->is_data = 0; } else { mydata->is_data = 1; } zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata); if (actual_alias) { phar_archive_data *fd_ptr; if (!phar_validate_alias(actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } mydata->is_temporary_alias = 0; if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias; if (entry.is_persistent) { efree(actual_alias); } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); } else { phar_archive_data *fd_ptr; if (alias_len) { if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname); } zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent); mydata->alias_len = alias_len; } else { mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = fname_len; } mydata->is_temporary_alias = 1; } if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ Commit Message: Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile (cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2) CWE ID: CWE-119 Target: 1 Example 2: Code: inline void writeit(int f, void *buf, size_t len) { ssize_t res; while (len > 0) { DEBUG("+"); if ((res = write(f, buf, len)) <= 0) err("Send failed: %m"); len -= res; buf += res; } } Commit Message: Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh. 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 v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!htmlDocument->hasNamedItem(key.impl()) && !htmlDocument->hasExtraNamedItem(key.impl())) return v8Undefined(); RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key); if (items->isEmpty()) return v8Undefined(); if (items->hasExactlyOneItem()) { Node* node = items->item(0); Frame* frame = 0; if (node->hasTagName(HTMLNames::iframeTag) && (frame = toHTMLIFrameElement(node)->contentFrame())) return toV8(frame->domWindow(), creationContext, isolate); return toV8(node, creationContext, isolate); } return toV8(items.release(), creationContext, isolate); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: static base::Callback<void(const gfx::Image&)> Wrap( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) { auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()), base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds)); return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr()); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119 Target: 1 Example 2: Code: int send_xmessage_using_uids(struct proclistlist *pll, char *message){ int num_users; int lokke; int *uids=get_userlist(pll,&num_users); for(lokke=0;lokke<num_users;lokke++){ char xauthpath[5000]; struct passwd *pass=getpwuid(uids[lokke]); sprintf(xauthpath,"%s/.Xauthority",pass->pw_dir); if(send_xmessage(xauthpath,message)==1){ free(uids); return 1; } } free(uids); return 0; } Commit Message: Fix memory overflow if the name of an environment is larger than 500 characters. Bug found by Adam Sampson. 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 vnc_write_u16(VncState *vs, uint16_t value) { uint8_t buf[2]; buf[0] = (value >> 8) & 0xFF; buf[1] = value & 0xFF; vnc_write(vs, buf, 2); } Commit Message: 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: static v8::Handle<v8::Value> overloadedMethod3Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod3"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->overloadedMethod(strArg); 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 compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = *dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } Commit Message: netfilter: add back stackpointer size checks The rationale for removing the check is only correct for rulesets generated by ip(6)tables. In iptables, a jump can only occur to a user-defined chain, i.e. because we size the stack based on number of user-defined chains we cannot exceed stack size. However, the underlying binary format has no such restriction, and the validation step only ensures that the jump target is a valid rule start point. IOW, its possible to build a rule blob that has no user-defined chains but does contain a jump. If this happens, no jump stack gets allocated and crash occurs because no jumpstack was allocated. Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset") Reported-by: [email protected] Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[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: status_t DRMSource::start(MetaData *params) { int32_t val; if (params && params->findInt32(kKeyWantsNALFragments, &val) && val != 0) { mWantsNALFragments = true; } else { mWantsNALFragments = false; } return mOriginalMediaSource->start(params); } Commit Message: Fix security vulnerability in libstagefright bug: 28175045 Change-Id: Icee6c7eb5b761da4aa3e412fb71825508d74d38f 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 PdfCompositorClient::Composite( service_manager::Connector* connector, base::SharedMemoryHandle handle, size_t data_size, mojom::PdfCompositor::CompositePdfCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_task_runner) { DCHECK(data_size); if (!compositor_) Connect(connector); mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(handle, data_size, true); compositor_->CompositePdf( std::move(buffer_handle), base::BindOnce(&OnCompositePdf, base::Passed(&compositor_), std::move(callback), callback_task_runner)); } 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: void GLES2DecoderImpl::DoBindBuffer(GLenum target, GLuint client_id) { BufferManager::BufferInfo* info = NULL; GLuint service_id = 0; if (client_id != 0) { info = GetBufferInfo(client_id); if (!info) { if (!group_->bind_generates_resource()) { LOG(ERROR) << "glBindBuffer: id not generated by glGenBuffers"; current_decoder_error_ = error::kGenericError; return; } glGenBuffersARB(1, &service_id); CreateBufferInfo(client_id, service_id); info = GetBufferInfo(client_id); IdAllocatorInterface* id_allocator = group_->GetIdAllocator(id_namespaces::kBuffers); id_allocator->MarkAsUsed(client_id); } } if (info) { if (!buffer_manager()->SetTarget(info, target)) { SetGLError(GL_INVALID_OPERATION, "glBindBuffer: buffer bound to more than 1 target"); return; } service_id = info->service_id(); } switch (target) { case GL_ARRAY_BUFFER: bound_array_buffer_ = info; break; case GL_ELEMENT_ARRAY_BUFFER: bound_element_array_buffer_ = info; break; default: NOTREACHED(); // Validation should prevent us getting here. break; } glBindBuffer(target, service_id); } Commit Message: Always write data to new buffer in SimulateAttrib0 This is to work around linux nvidia driver bug. TEST=asan BUG=118970 Review URL: http://codereview.chromium.org/10019003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131538 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: void GLES2Implementation::CommitOverlayPlanesCHROMIUM(uint64_t swap_id, uint32_t flags) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] CommitOverlayPlanesCHROMIUM()"); TRACE_EVENT0("gpu", "GLES2::CommitOverlayPlanesCHROMIUM"); swap_buffers_tokens_.push(helper_->InsertToken()); helper_->CommitOverlayPlanesCHROMIUM(swap_id, flags); helper_->CommandBufferHelper::Flush(); if (swap_buffers_tokens_.size() > kMaxSwapBuffers + 1) { helper_->WaitForToken(swap_buffers_tokens_.front()); swap_buffers_tokens_.pop(); } } 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 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: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string ) { cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) c = c->next; return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void __init vfs_caches_init_early(void) { int i; for (i = 0; i < ARRAY_SIZE(in_lookup_hashtable); i++) INIT_HLIST_BL_HEAD(&in_lookup_hashtable[i]); dcache_init_early(); inode_init_early(); } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[email protected]> 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: static int path_has_protocol(const char *path) { const char *p; #ifdef _WIN32 if (is_windows_drive(path) || is_windows_drive_prefix(path)) { return 0; } p = path + strcspn(path, ":/\\"); #else p = path + strcspn(path, ":/"); #endif return *p == ':'; } Commit Message: CWE ID: CWE-190 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: check_symlinks(struct archive_write_disk *a) { #if !defined(HAVE_LSTAT) /* Platform doesn't have lstat, so we can't look for symlinks. */ (void)a; /* UNUSED */ return (ARCHIVE_OK); #else char *pn; char c; int r; struct stat st; /* * Guard against symlink tricks. Reject any archive entry whose * destination would be altered by a symlink. */ /* Whatever we checked last time doesn't need to be re-checked. */ pn = a->name; if (archive_strlen(&(a->path_safe)) > 0) { char *p = a->path_safe.s; while ((*pn != '\0') && (*p == *pn)) ++p, ++pn; } /* Skip the root directory if the path is absolute. */ if(pn == a->name && pn[0] == '/') ++pn; c = pn[0]; /* Keep going until we've checked the entire name. */ while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) { /* Skip the next path element. */ while (*pn != '\0' && *pn != '/') ++pn; c = pn[0]; pn[0] = '\0'; /* Check that we haven't hit a symlink. */ r = lstat(a->name, &st); if (r != 0) { /* We've hit a dir that doesn't exist; stop now. */ if (errno == ENOENT) { break; } else { /* Note: This effectively disables deep directory * support when security checks are enabled. * Otherwise, very long pathnames that trigger * an error here could evade the sandbox. * TODO: We could do better, but it would probably * require merging the symlink checks with the * deep-directory editing. */ return (ARCHIVE_FAILED); } } else if (S_ISLNK(st.st_mode)) { if (c == '\0') { /* * Last element is symlink; remove it * so we can overwrite it with the * item being extracted. */ if (unlink(a->name)) { archive_set_error(&a->archive, errno, "Could not remove symlink %s", a->name); pn[0] = c; return (ARCHIVE_FAILED); } a->pst = NULL; /* * Even if we did remove it, a warning * is in order. The warning is silly, * though, if we're just replacing one * symlink with another symlink. */ if (!S_ISLNK(a->mode)) { archive_set_error(&a->archive, 0, "Removing symlink %s", a->name); } /* Symlink gone. No more problem! */ pn[0] = c; return (0); } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) { /* User asked us to remove problems. */ if (unlink(a->name) != 0) { archive_set_error(&a->archive, 0, "Cannot remove intervening symlink %s", a->name); pn[0] = c; return (ARCHIVE_FAILED); } a->pst = NULL; } else { archive_set_error(&a->archive, 0, "Cannot extract through symlink %s", a->name); pn[0] = c; return (ARCHIVE_FAILED); } } pn[0] = c; if (pn[0] != '\0') pn++; /* Advance to the next segment. */ } pn[0] = c; /* We've checked and/or cleaned the whole path, so remember it. */ archive_strcpy(&a->path_safe, a->name); return (ARCHIVE_OK); #endif } Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert. CWE ID: CWE-20 Target: 1 Example 2: Code: GF_Err npck_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NPCKBox *ptr = (GF_NPCKBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nbPackets); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) 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: const char* WinPKIErrorString(void) { static char error_string[64]; DWORD error_code = GetLastError(); if ((error_code >> 16) != 0x8009) return WindowsErrorString(); switch (error_code) { case NTE_BAD_UID: return "Bad UID."; case CRYPT_E_MSG_ERROR: return "An error occurred while performing an operation on a cryptographic message."; case CRYPT_E_UNKNOWN_ALGO: return "Unknown cryptographic algorithm."; case CRYPT_E_INVALID_MSG_TYPE: return "Invalid cryptographic message type."; case CRYPT_E_HASH_VALUE: return "The hash value is not correct"; case CRYPT_E_ISSUER_SERIALNUMBER: return "Invalid issuer and/or serial number."; case CRYPT_E_BAD_LEN: return "The length specified for the output data was insufficient."; case CRYPT_E_BAD_ENCODE: return "An error occurred during encode or decode operation."; case CRYPT_E_FILE_ERROR: return "An error occurred while reading or writing to a file."; case CRYPT_E_NOT_FOUND: return "Cannot find object or property."; case CRYPT_E_EXISTS: return "The object or property already exists."; case CRYPT_E_NO_PROVIDER: return "No provider was specified for the store or object."; case CRYPT_E_DELETED_PREV: return "The previous certificate or CRL context was deleted."; case CRYPT_E_NO_MATCH: return "Cannot find the requested object."; case CRYPT_E_UNEXPECTED_MSG_TYPE: case CRYPT_E_NO_KEY_PROPERTY: case CRYPT_E_NO_DECRYPT_CERT: return "Private key or certificate issue"; case CRYPT_E_BAD_MSG: return "Not a cryptographic message."; case CRYPT_E_NO_SIGNER: return "The signed cryptographic message does not have a signer for the specified signer index."; case CRYPT_E_REVOKED: return "The certificate is revoked."; case CRYPT_E_NO_REVOCATION_DLL: case CRYPT_E_NO_REVOCATION_CHECK: case CRYPT_E_REVOCATION_OFFLINE: case CRYPT_E_NOT_IN_REVOCATION_DATABASE: return "Cannot check certificate revocation."; case CRYPT_E_INVALID_NUMERIC_STRING: case CRYPT_E_INVALID_PRINTABLE_STRING: case CRYPT_E_INVALID_IA5_STRING: case CRYPT_E_INVALID_X500_STRING: case CRYPT_E_NOT_CHAR_STRING: return "Invalid string."; case CRYPT_E_SECURITY_SETTINGS: return "The cryptographic operation failed due to a local security option setting."; case CRYPT_E_NO_VERIFY_USAGE_CHECK: case CRYPT_E_VERIFY_USAGE_OFFLINE: return "Cannot complete usage check."; case CRYPT_E_NO_TRUSTED_SIGNER: return "None of the signers of the cryptographic message or certificate trust list is trusted."; default: static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code); return error_string; } } Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768 * This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as it is described per its revision 11, which is the latest revision at the time of this commit, by disabling Windows prompts, enacted during signature validation, that allow the user to bypass the intended signature verification checks. * It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed certificate"), which relies on the end-user actively ignoring a Windows prompt that tells them that the update failed the signature validation whilst also advising against running it, is being fully addressed, even as the update protocol remains HTTP. * It also need to be pointed out that the extended delay (48 hours) between the time the vulnerability was reported and the moment it is fixed in our codebase has to do with the fact that the reporter chose to deviate from standard security practices by not disclosing the details of the vulnerability with us, be it publicly or privately, before creating the cert.org report. The only advance notification we received was a generic note about the use of HTTP vs HTTPS, which, as have established, is not immediately relevant to addressing the reported vulnerability. * Closes #1009 * Note: The other vulnerability scenario described towards the end of #1009, which doesn't have to do with the "lack of CA checking", will be addressed separately. CWE ID: CWE-494 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 vmx_set_constant_host_state(struct vcpu_vmx *vmx) { u32 low32, high32; unsigned long tmpl; struct desc_ptr dt; vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */ vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */ vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */ vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ #ifdef CONFIG_X86_64 /* * Load null selectors, so we can avoid reloading them in * __vmx_load_host_state(), in case userspace uses the null selectors * too (the expected case). */ vmcs_write16(HOST_DS_SELECTOR, 0); vmcs_write16(HOST_ES_SELECTOR, 0); #else vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ #endif vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ native_store_idt(&dt); vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */ vmx->host_idt_base = dt.address; vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */ rdmsr(MSR_IA32_SYSENTER_CS, low32, high32); vmcs_write32(HOST_IA32_SYSENTER_CS, low32); rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl); vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */ if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, low32, high32); vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); } } 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: 1 Example 2: Code: static int proc_id_map_release(struct inode *inode, struct file *file) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; put_user_ns(ns); return seq_release(inode, file); } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <[email protected]> Cc: Emese Revfy <[email protected]> Cc: Pax Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Mateusz Guzik <[email protected]> Cc: Alexey Dobriyan <[email protected]> Cc: Cyrill Gorcunov <[email protected]> Cc: Jarod Wilson <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: static int simulate_llsc(struct pt_regs *regs, unsigned int opcode) { if ((opcode & OPCODE) == LL) { perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); return simulate_ll(regs, opcode); } if ((opcode & OPCODE) == SC) { perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); return simulate_sc(regs, opcode); } return -1; /* Must be something else ... */ } 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: make_size_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, png_byte PNG_CONST bit_depth, int PNG_CONST interlace_type, png_uint_32 PNG_CONST w, png_uint_32 PNG_CONST h, int PNG_CONST do_interlace) { context(ps, fault); /* At present libpng does not support the write of an interlaced image unless * PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the code here * does the pixel interlace itself, so: */ check_interlace_type(interlace_type); Try { png_infop pi; png_structp pp; unsigned int pixel_size; /* Make a name and get an appropriate id for the store: */ char name[FILE_NAME_SIZE]; PNG_CONST png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/, interlace_type, w, h, do_interlace); standard_name_from_id(name, sizeof name, 0, id); pp = set_store_for_write(ps, &pi, name); /* In the event of a problem return control to the Catch statement below * to do the clean up - it is not possible to 'return' directly from a Try * block. */ if (pp == NULL) Throw ps; png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef PNG_TEXT_SUPPORTED { static char key[] = "image name"; /* must be writeable */ size_t pos; png_text text; char copy[FILE_NAME_SIZE]; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; /* Yuck: the text must be writable! */ pos = safecat(copy, sizeof copy, 0, ps->wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); png_write_info(pp, pi); /* Calculate the bit size, divide by 8 to get the byte size - this won't * overflow because we know the w values are all small enough even for * a system where 'unsigned int' is only 16 bits. */ pixel_size = bit_size(pp, colour_type, bit_depth); if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8) png_error(pp, "row size incorrect"); else { int npasses = npasses_from_interlace_type(pp, interlace_type); png_uint_32 y; int pass; # ifdef PNG_WRITE_FILTER_SUPPORTED int nfilter = PNG_FILTER_VALUE_LAST; # endif png_byte image[16][SIZE_ROWMAX]; /* To help consistent error detection make the parts of this buffer * that aren't set below all '1': */ memset(image, 0xff, sizeof image); if (!do_interlace && npasses != png_set_interlace_handling(pp)) png_error(pp, "write: png_set_interlace_handling failed"); /* Prepare the whole image first to avoid making it 7 times: */ for (y=0; y<h; ++y) size_row(image[y], w * pixel_size, y); for (pass=0; pass<npasses; ++pass) { /* The following two are for checking the macros: */ PNG_CONST png_uint_32 wPass = PNG_PASS_COLS(w, pass); /* If do_interlace is set we don't call png_write_row for every * row because some of them are empty. In fact, for a 1x1 image, * most of them are empty! */ for (y=0; y<h; ++y) { png_const_bytep row = image[y]; png_byte tempRow[SIZE_ROWMAX]; /* If do_interlace *and* the image is interlaced we * need a reduced interlace row; this may be reduced * to empty. */ if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7) { /* The row must not be written if it doesn't exist, notice * that there are two conditions here, either the row isn't * ever in the pass or the row would be but isn't wide * enough to contribute any pixels. In fact the wPass test * can be used to skip the whole y loop in this case. */ if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0) { /* Set to all 1's for error detection (libpng tends to * set unset things to 0). */ memset(tempRow, 0xff, sizeof tempRow); interlace_row(tempRow, row, pixel_size, w, pass); row = tempRow; } else continue; } # ifdef PNG_WRITE_FILTER_SUPPORTED /* Only get to here if the row has some pixels in it, set the * filters to 'all' for the very first row and thereafter to a * single filter. It isn't well documented, but png_set_filter * does accept a filter number (per the spec) as well as a bit * mask. * * The apparent wackiness of decrementing nfilter rather than * incrementing is so that Paeth gets used in all images bigger * than 1 row - it's the tricky one. */ png_set_filter(pp, 0/*method*/, nfilter >= PNG_FILTER_VALUE_LAST ? PNG_ALL_FILTERS : nfilter); if (nfilter-- == 0) nfilter = PNG_FILTER_VALUE_LAST-1; # endif png_write_row(pp, row); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, id); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } } 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: static void __bio_unmap_user(struct bio *bio) { struct bio_vec *bvec; int i; /* * make sure we dirty pages we wrote to */ bio_for_each_segment_all(bvec, bio, i) { if (bio_data_dir(bio) == READ) set_page_dirty_lock(bvec->bv_page); put_page(bvec->bv_page); } bio_put(bio); } Commit Message: fix unbalanced page refcounting in bio_map_user_iov bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if IO vector has small consecutive buffers belonging to the same page. bio_add_pc_page merges them into one, but the page reference is never dropped. Cc: [email protected] Signed-off-by: Vitaly Mayatskikh <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-772 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: ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); if (entry > bin->size || entry + sizeof (b) > bin->size) return 0; i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; } Commit Message: Fix null deref and uaf in mach0 parser 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: SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: void P2PSocketDispatcherHost::SendNetworkList( int routing_id, const net::NetworkInterfaceList& list) { Send(new P2PMsg_NetworkList(routing_id, list)); } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 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: image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); } 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: static int unix_dgram_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock_iocb *siocb = kiocb_to_siocb(kiocb); struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); struct sockaddr_un *sunaddr = msg->msg_name; struct sock *other = NULL; int namelen = 0; /* fake GCC */ int err; unsigned int hash; struct sk_buff *skb; long timeo; struct scm_cookie tmp_scm; int max_level; int data_len = 0; if (NULL == siocb->scm) siocb->scm = &tmp_scm; wait_for_unix_gc(); err = scm_send(sock, msg, siocb->scm); if (err < 0) return err; err = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto out; if (msg->msg_namelen) { err = unix_mkname(sunaddr, msg->msg_namelen, &hash); if (err < 0) goto out; namelen = err; } else { sunaddr = NULL; err = -ENOTCONN; other = unix_peer_get(sk); if (!other) goto out; } if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr && (err = unix_autobind(sock)) != 0) goto out; err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; if (len > SKB_MAX_ALLOC) data_len = min_t(size_t, len - SKB_MAX_ALLOC, MAX_SKB_FRAGS * PAGE_SIZE); skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; err = unix_scm_to_skb(siocb->scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; unix_get_secdata(siocb->scm, skb); skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iovec(skb, 0, msg->msg_iov, 0, len); if (err) goto out_free; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); restart: if (!other) { err = -ECONNRESET; if (sunaddr == NULL) goto out_free; other = unix_find_other(net, sunaddr, namelen, sk->sk_type, hash, &err); if (other == NULL) goto out_free; } if (sk_filter(other, skb) < 0) { /* Toss the packet but do not return any error to the sender */ err = len; goto out_free; } unix_state_lock(other); err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; if (sock_flag(other, SOCK_DEAD)) { /* * Check with 1003.1g - what should * datagram error */ unix_state_unlock(other); sock_put(other); err = 0; unix_state_lock(sk); if (unix_peer(sk) == other) { unix_peer(sk) = NULL; unix_state_unlock(sk); unix_dgram_disconnected(sk, other); sock_put(other); err = -ECONNREFUSED; } else { unix_state_unlock(sk); } other = NULL; if (err) goto out_free; goto restart; } err = -EPIPE; if (other->sk_shutdown & RCV_SHUTDOWN) goto out_unlock; if (sk->sk_type != SOCK_SEQPACKET) { err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } if (unix_peer(other) != sk && unix_recvq_full(other)) { if (!timeo) { err = -EAGAIN; goto out_unlock; } timeo = unix_wait_for_peer(other, timeo); err = sock_intr_errno(timeo); if (signal_pending(current)) goto out_free; goto restart; } if (sock_flag(other, SOCK_RCVTSTAMP)) __net_timestamp(skb); maybe_add_creds(skb, sock, other); skb_queue_tail(&other->sk_receive_queue, skb); if (max_level > unix_sk(other)->recursion_level) unix_sk(other)->recursion_level = max_level; unix_state_unlock(other); other->sk_data_ready(other, len); sock_put(other); scm_destroy(siocb->scm); return len; out_unlock: unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(siocb->scm); return err; } Commit Message: af_netlink: force credentials passing [CVE-2012-3520] Pablo Neira Ayuso discovered that avahi and potentially NetworkManager accept spoofed Netlink messages because of a kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data to the receiver if the sender did not provide such data, instead of not including any such data at all or including the correct data from the peer (as it is the case with AF_UNIX). This bug was introduced in commit 16e572626961 (af_unix: dont send SCM_CREDENTIALS by default) This patch forces passing credentials for netlink, as before the regression. Another fix would be to not add SCM_CREDENTIALS in netlink messages if not provided by the sender, but it might break some programs. With help from Florian Weimer & Petr Matousek This issue is designated as CVE-2012-3520 Signed-off-by: Eric Dumazet <[email protected]> Cc: Petr Matousek <[email protected]> Cc: Florian Weimer <[email protected]> Cc: Pablo Neira Ayuso <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-287 Target: 1 Example 2: Code: void OMXCodec::initNativeWindowCrop() { int32_t left, top, right, bottom; CHECK(mOutputFormat->findRect( kKeyCropRect, &left, &top, &right, &bottom)); android_native_rect_t crop; crop.left = left; crop.top = top; crop.right = right + 1; crop.bottom = bottom + 1; native_window_set_crop(mNativeWindow.get(), &crop); } Commit Message: OMXCodec: check IMemory::pointer() before using allocation Bug: 29421811 Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1 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: gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id, double file_gamma, double screen_gamma, png_byte sbit, int threshold_test, int use_input_precision, int scale16, int expand16, int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color, double background_gamma) { /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->file_gamma = file_gamma; dp->screen_gamma = screen_gamma; dp->background_gamma = background_gamma; dp->sbit = sbit; dp->threshold_test = threshold_test; dp->use_input_precision = use_input_precision; dp->scale16 = scale16; dp->expand16 = expand16; dp->do_background = do_background; if (do_background && pointer_to_the_background_color != 0) dp->background_color = *pointer_to_the_background_color; else memset(&dp->background_color, 0, sizeof dp->background_color); /* Local variable fields */ dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0; } 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 get_sda(void) { return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1); } 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: dissect_DRIVER_INFO_3(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { proto_tree *subtree; int struct_start = offset; subtree = proto_tree_add_subtree( tree, tvb, offset, 0, ett_DRIVER_INFO_3, NULL, "Driver info level 3"); offset = dissect_ndr_uint32(tvb, offset, pinfo, subtree, di, drep, hf_driverinfo_cversion, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_drivername, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_environment, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_driverpath, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_datafile, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_configfile, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_helpfile, struct_start, NULL); offset = dissect_spoolss_relstrarray( tvb, offset, pinfo, subtree, di, drep, hf_dependentfiles, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_monitorname, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_defaultdatatype, struct_start, 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: auth_pin_reset_oberthur_style(struct sc_card *card, unsigned int type, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); struct sc_pin_cmd_data pin_cmd; struct sc_path tmp_path; struct sc_file *tmp_file = NULL; struct sc_apdu apdu; unsigned char puk[OBERTHUR_AUTH_MAX_LENGTH_PUK]; unsigned char ffs1[0x100]; int rv, rvv, local_pin_reference; LOG_FUNC_CALLED(card->ctx); local_pin_reference = data->pin_reference & ~OBERTHUR_PIN_LOCAL; if (data->pin_reference != OBERTHUR_PIN_REFERENCE_USER) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Oberthur style 'PIN RESET' failed: invalid PIN reference"); memset(&pin_cmd, 0, sizeof(pin_cmd)); memset(&tmp_path, 0, sizeof(struct sc_path)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.cmd = SC_PIN_CMD_VERIFY; pin_cmd.pin_reference = OBERTHUR_PIN_REFERENCE_PUK; memcpy(&pin_cmd.pin1, &data->pin1, sizeof(pin_cmd.pin1)); rv = auth_pin_verify(card, SC_AC_CHV, &pin_cmd, tries_left); LOG_TEST_RET(card->ctx, rv, "Oberthur style 'PIN RESET' failed: SOPIN verify error"); sc_format_path("2000", &tmp_path); tmp_path.type = SC_PATH_TYPE_FILE_ID; rv = iso_ops->select_file(card, &tmp_path, &tmp_file); LOG_TEST_RET(card->ctx, rv, "select PUK file"); if (!tmp_file || tmp_file->size < OBERTHUR_AUTH_MAX_LENGTH_PUK) LOG_TEST_RET(card->ctx, SC_ERROR_FILE_TOO_SMALL, "Oberthur style 'PIN RESET' failed"); rv = iso_ops->read_binary(card, 0, puk, OBERTHUR_AUTH_MAX_LENGTH_PUK, 0); LOG_TEST_RET(card->ctx, rv, "read PUK file error"); if (rv != OBERTHUR_AUTH_MAX_LENGTH_PUK) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_DATA, "Oberthur style 'PIN RESET' failed"); memset(ffs1, 0xFF, sizeof(ffs1)); memcpy(ffs1, puk, rv); memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.cmd = SC_PIN_CMD_UNBLOCK; pin_cmd.pin_reference = local_pin_reference; auth_init_pin_info(card, &pin_cmd.pin1, OBERTHUR_AUTH_TYPE_PUK); pin_cmd.pin1.data = ffs1; pin_cmd.pin1.len = OBERTHUR_AUTH_MAX_LENGTH_PUK; if (data->pin2.data) { memcpy(&pin_cmd.pin2, &data->pin2, sizeof(pin_cmd.pin2)); rv = auth_pin_reset(card, SC_AC_CHV, &pin_cmd, tries_left); LOG_FUNC_RETURN(card->ctx, rv); } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x00, local_pin_reference); apdu.lc = OBERTHUR_AUTH_MAX_LENGTH_PIN + OBERTHUR_AUTH_MAX_LENGTH_PUK; apdu.datalen = OBERTHUR_AUTH_MAX_LENGTH_PIN + OBERTHUR_AUTH_MAX_LENGTH_PUK; apdu.data = ffs1; pin_cmd.apdu = &apdu; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_IMPLICIT_CHANGE; pin_cmd.pin1.min_length = 4; pin_cmd.pin1.max_length = 8; pin_cmd.pin1.encoding = SC_PIN_ENCODING_ASCII; pin_cmd.pin1.offset = 5; pin_cmd.pin2.data = &ffs1[OBERTHUR_AUTH_MAX_LENGTH_PUK]; pin_cmd.pin2.len = OBERTHUR_AUTH_MAX_LENGTH_PIN; pin_cmd.pin2.offset = 5 + OBERTHUR_AUTH_MAX_LENGTH_PUK; pin_cmd.pin2.min_length = 4; pin_cmd.pin2.max_length = 8; pin_cmd.pin2.encoding = SC_PIN_ENCODING_ASCII; rvv = iso_drv->ops->pin_cmd(card, &pin_cmd, tries_left); if (rvv) sc_log(card->ctx, "%s: PIN CMD 'VERIFY' with pinpad failed", sc_strerror(rvv)); if (auth_current_ef) rv = iso_ops->select_file(card, &auth_current_ef->path, &auth_current_ef); if (rv > 0) rv = 0; LOG_FUNC_RETURN(card->ctx, rv ? rv: rvv); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. 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: static void rekey_seq_generator(struct work_struct *work) { struct keydata *keyptr = &ip_keydata[1 ^ (ip_cnt & 1)]; get_random_bytes(keyptr->secret, sizeof(keyptr->secret)); keyptr->count = (ip_cnt & COUNT_MASK) << HASH_BITS; smp_wmb(); ip_cnt++; schedule_delayed_work(&rekey_work, round_jiffies_relative(REKEY_INTERVAL)); } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: __ip_vs_service_find(struct net *net, int af, __u16 protocol, const union nf_inet_addr *vaddr, __be16 vport) { unsigned int hash; struct ip_vs_service *svc; /* Check for "full" addressed entries */ hash = ip_vs_svc_hashkey(net, af, protocol, vaddr, vport); list_for_each_entry(svc, &ip_vs_svc_table[hash], s_list){ if ((svc->af == af) && ip_vs_addr_equal(af, &svc->addr, vaddr) && (svc->port == vport) && (svc->protocol == protocol) && net_eq(svc->net, net)) { /* HIT */ return svc; } } return NULL; } Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT) If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is not set, __ip_vs_get_timeouts() does not fully initialize the structure that gets copied to userland and that for leaks up to 12 bytes of kernel stack. Add an explicit memset(0) before passing the structure to __ip_vs_get_timeouts() to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Wensong Zhang <[email protected]> Cc: Simon Horman <[email protected]> Cc: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec, dec_slice_params_t * ps_slice, UWORD16 u2_first_mb_in_slice) { UWORD8 uc_more_data_flag; UWORD8 u1_num_mbs, u1_mb_idx; dec_mb_info_t *ps_cur_mb_info; deblk_mb_t *ps_cur_deblk_mb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; WORD16 i2_cur_mb_addr; UWORD8 u1_mbaff; UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb; WORD32 ret = OK; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mbaff = ps_slice->u1_mbaff_frame_flag; /* initializations */ u1_mb_idx = ps_dec->u1_mb_idx; u1_num_mbs = u1_mb_idx; uc_more_data_flag = 1; i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff; do { UWORD8 u1_mb_type; ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) { ret = ERROR_MB_ADDRESS_T; break; } ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_mb_info->u1_end_of_slice = 0; /***************************************************************/ /* Get the required information for decoding of MB */ /* mb_x, mb_y , neighbour availablity, */ /***************************************************************/ ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0); /***************************************************************/ /* Set the deblocking parameters for this MB */ /***************************************************************/ ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; if(ps_dec->u4_app_disable_deblk_frm == 0) ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB; /**************************************************************/ /* Macroblock Layer Begins, Decode the u1_mb_type */ /**************************************************************/ { UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst; UWORD32 u4_word, u4_ldz, u4_temp; /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf); u4_ldz = CLZ(u4_word); /* Flush the ps_bitstrm */ u4_bitstream_offset += (u4_ldz + 1); /* Read the suffix from the ps_bitstrm */ u4_word = 0; if(u4_ldz) GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf, u4_ldz); *pu4_bitstrm_ofst = u4_bitstream_offset; u4_temp = ((1 << u4_ldz) + u4_word - 1); if(u4_temp > 25) return ERROR_MB_TYPE; u1_mb_type = u4_temp; } ps_cur_mb_info->u1_mb_type = u1_mb_type; COPYTHECONTEXT("u1_mb_type", u1_mb_type); /**************************************************************/ /* Parse Macroblock data */ /**************************************************************/ if(25 == u1_mb_type) { /* I_PCM_MB */ ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB; ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = 0; } else { ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; } if(u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm); /* Store the colocated information */ { mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4); mv_pred_t s_mvPred = { { 0, 0, 0, 0 }, { -1, -1 }, 0, 0}; ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0, (UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4, 4); } /*if num _cores is set to 3,compute bs will be done in another thread*/ if(ps_dec->u4_num_cores < 3) { if(ps_dec->u4_app_disable_deblk_frm == 0) ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info, (UWORD16)(u1_num_mbs >> u1_mbaff)); } u1_num_mbs++; ps_dec->u2_total_mbs_coded++; /****************************************************************/ /* Check for End Of Row */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || (!uc_more_data_flag); ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag); /*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d", ps_slice->i4_poc >> ps_slice->u1_field_pic_flag, ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb)); H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/ if(u1_tfr_n_mb || (!uc_more_data_flag)) { if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } while(uc_more_data_flag); ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - (u2_first_mb_in_slice << u1_mbaff); return ret; } Commit Message: Decoder Update mb count after mb map is set. Bug: 25928803 Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37 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 perf_swevent_overflow(struct perf_event *event, u64 overflow, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; int throttle = 0; data->period = event->hw.last_period; if (!overflow) overflow = perf_swevent_set_period(event); if (hwc->interrupts == MAX_INTERRUPTS) return; for (; overflow; overflow--) { if (__perf_event_overflow(event, nmi, throttle, data, regs)) { /* * We inhibit the overflow from happening when * hwc->interrupts == MAX_INTERRUPTS. */ break; } throttle = 1; } } 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 Target: 1 Example 2: Code: static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages) { struct qstr this = QSTR_INIT("[aio]", 5); struct file *file; struct path path; struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb); if (IS_ERR(inode)) return ERR_CAST(inode); inode->i_mapping->a_ops = &aio_ctx_aops; inode->i_mapping->private_data = ctx; inode->i_size = PAGE_SIZE * nr_pages; path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this); if (!path.dentry) { iput(inode); return ERR_PTR(-ENOMEM); } path.mnt = mntget(aio_mnt); d_instantiate(path.dentry, inode); file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops); if (IS_ERR(file)) { path_put(&path); return file; } file->f_flags = O_RDWR; return file; } Commit Message: aio: mark AIO pseudo-fs noexec This ensures that do_mmap() won't implicitly make AIO memory mappings executable if the READ_IMPLIES_EXEC personality flag is set. Such behavior is problematic because the security_mmap_file LSM hook doesn't catch this case, potentially permitting an attacker to bypass a W^X policy enforced by SELinux. I have tested the patch on my machine. To test the behavior, compile and run this: #define _GNU_SOURCE #include <unistd.h> #include <sys/personality.h> #include <linux/aio_abi.h> #include <err.h> #include <stdlib.h> #include <stdio.h> #include <sys/syscall.h> int main(void) { personality(READ_IMPLIES_EXEC); aio_context_t ctx = 0; if (syscall(__NR_io_setup, 1, &ctx)) err(1, "io_setup"); char cmd[1000]; sprintf(cmd, "cat /proc/%d/maps | grep -F '/[aio]'", (int)getpid()); system(cmd); return 0; } In the output, "rw-s" is good, "rwxs" is bad. Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[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: perform_transform_test(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, 0)) { png_uint_32 counter = 0; size_t base_pos; char name[64]; base_pos = safecat(name, sizeof name, 0, "transform:"); for (;;) { size_t pos = base_pos; PNG_CONST image_transform *list = 0; /* 'max' is currently hardwired to '1'; this should be settable on the * command line. */ counter = image_transform_add(&list, 1/*max*/, counter, name, sizeof name, &pos, colour_type, bit_depth); if (counter == 0) break; /* The command line can change this to checking interlaced images. */ do { pm->repeat = 0; transform_test(pm, FILEID(colour_type, bit_depth, palette_number, pm->interlace_type, 0, 0, 0), list, name); if (fail(pm)) return; } while (pm->repeat); } } } 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 Browser::TabDetachedAt(TabContents* contents, int index) { TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); } 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: 1 Example 2: Code: static void hash_hw_write_key(struct hash_device_data *device_data, const u8 *key, unsigned int keylen) { u32 word = 0; int nwords = 1; HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK); while (keylen >= 4) { u32 *key_word = (u32 *)key; HASH_SET_DIN(key_word, nwords); keylen -= 4; key += 4; } /* Take care of the remaining bytes in the last word */ if (keylen) { word = 0; while (keylen) { word |= (key[keylen - 1] << (8 * (keylen - 1))); keylen--; } HASH_SET_DIN(&word, nwords); } while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK) cpu_relax(); HASH_SET_DCAL; while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK) cpu_relax(); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[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: decode_time3(__be32 *p, struct timespec *time) { time->tv_sec = ntohl(*p++); time->tv_nsec = ntohl(*p++); return p; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 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 dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; } Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error Fixes: Null pointer dereference Fixes: CVE-2017-9608 Found-by: Yihan Lian Signed-off-by: Michael Niedermayer <[email protected]> (cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd) Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: BOOLEAN btif_hh_add_added_dev(bt_bdaddr_t bda, tBTA_HH_ATTR_MASK attr_mask) { int i; for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) { if (memcmp(&(btif_hh_cb.added_devices[i].bd_addr), &bda, BD_ADDR_LEN) == 0) { BTIF_TRACE_WARNING(" Device %02X:%02X:%02X:%02X:%02X:%02X already added", bda.address[0], bda.address[1], bda.address[2], bda.address[3], bda.address[4], bda.address[5]); return FALSE; } } for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) { if (btif_hh_cb.added_devices[i].bd_addr.address[0] == 0 && btif_hh_cb.added_devices[i].bd_addr.address[1] == 0 && btif_hh_cb.added_devices[i].bd_addr.address[2] == 0 && btif_hh_cb.added_devices[i].bd_addr.address[3] == 0 && btif_hh_cb.added_devices[i].bd_addr.address[4] == 0 && btif_hh_cb.added_devices[i].bd_addr.address[5] == 0) { BTIF_TRACE_WARNING(" Added device %02X:%02X:%02X:%02X:%02X:%02X", bda.address[0], bda.address[1], bda.address[2], bda.address[3], bda.address[4], bda.address[5]); memcpy(&(btif_hh_cb.added_devices[i].bd_addr), &bda, BD_ADDR_LEN); btif_hh_cb.added_devices[i].dev_handle = BTA_HH_INVALID_HANDLE; btif_hh_cb.added_devices[i].attr_mask = attr_mask; return TRUE; } } BTIF_TRACE_WARNING("%s: Error, out of space to add device",__FUNCTION__); return FALSE; } 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 svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc) { struct ib_cqe *cqe = wc->wr_cqe; struct svc_rdma_op_ctxt *ctxt; svc_rdma_send_wc_common_put(cq, wc, "write"); ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe); svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 0); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 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: mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } Commit Message: CVE-2017-13023/IPv6 mobility: Add a bounds check before fetching data 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), modified so the capture file won't cause 'tcpdump: pcap_loop: truncated dump file' CWE ID: CWE-125 Target: 1 Example 2: Code: static int proc_task_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = d_inode(dentry); struct task_struct *p = get_proc_task(inode); generic_fillattr(inode, stat); if (p) { stat->nlink += get_nr_threads(p); put_task_struct(p); } return 0; } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <[email protected]> Cc: Emese Revfy <[email protected]> Cc: Pax Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Mateusz Guzik <[email protected]> Cc: Alexey Dobriyan <[email protected]> Cc: Cyrill Gorcunov <[email protected]> Cc: Jarod Wilson <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: static void anotherStringAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValueString(info, imp->fastGetAttribute(HTMLNames::ReflectUrlAttributeAsAStringAttr), 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 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 isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove; } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119 Target: 1 Example 2: Code: static void on_recv_pkg(nw_ses *ses, void *data, size_t size) { struct clt_info *info = ses->privdata; ws_svr *svr = ws_svr_from_ses(ses); info->last_activity = current_timestamp(); if (!info->upgrade) { size_t nparsed = http_parser_execute(&info->parser, &svr->settings, data, size); if (!info->parser.upgrade && nparsed != size) { log_error("peer: %s http parse error: %s (%s)", nw_sock_human_addr(&ses->peer_addr), http_errno_description(HTTP_PARSER_ERRNO(&info->parser)), http_errno_name(HTTP_PARSER_ERRNO(&info->parser))); nw_svr_close_clt(svr->raw_svr, ses); } return; } switch (info->frame.opcode) { case 0x8: nw_svr_close_clt(svr->raw_svr, ses); return; case 0x9: send_pong_message(ses); return; case 0xa: return; } if (info->message == NULL) info->message = sdsempty(); info->message = sdscatlen(info->message, info->frame.payload, info->frame.payload_len); if (info->frame.fin) { int ret = svr->type.on_message(ses, info->remote, info->url, info->message, sdslen(info->message)); if (ses->id != 0) { if (ret < 0) { nw_svr_close_clt(svr->raw_svr, ses); } else { sdsfree(info->message); info->message = NULL; } } } } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows 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: static void l2cap_info_timeout(unsigned long arg) { struct l2cap_conn *conn = (void *) arg; conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE; conn->info_ident = 0; l2cap_conn_start(conn); } Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode Add support to config_req and config_rsp to configure ERTM and Streaming mode. If the remote device specifies ERTM or Streaming mode, then the same mode is proposed. Otherwise ERTM or Basic mode is used. And in case of a state 2 device, the remote device should propose the same mode. If not, then the channel gets disconnected. Signed-off-by: Gustavo F. Padovan <[email protected]> Signed-off-by: Marcel Holtmann <[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: txid_snapshot_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); TxidSnapshot *snap; txid last = 0; int nxip; int i; int avail; int expect; txid xmin, xmax; /* * load nxip and check for nonsense. * * (nxip > avail) check is against int overflows in 'expect'. */ nxip = pq_getmsgint(buf, 4); avail = buf->len - buf->cursor; expect = 8 + 8 + nxip * 8; if (nxip < 0 || nxip > avail || expect > avail) goto bad_format; xmin = pq_getmsgint64(buf); xmax = pq_getmsgint64(buf); if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID) goto bad_format; snap = palloc(TXID_SNAPSHOT_SIZE(nxip)); snap->xmin = xmin; snap->xmax = xmax; snap->nxip = nxip; SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip)); for (i = 0; i < nxip; i++) { txid cur = pq_getmsgint64(buf); if (cur <= last || cur < xmin || cur >= xmax) goto bad_format; snap->xip[i] = cur; last = cur; } PG_RETURN_POINTER(snap); bad_format: elog(ERROR, "invalid snapshot data"); return (Datum) NULL; } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189 Target: 1 Example 2: Code: MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickSignature); image->color_profile.length=clone_image->color_profile.length; image->color_profile.info=clone_image->color_profile.info; image->iptc_profile.length=clone_image->iptc_profile.length; image->iptc_profile.info=clone_image->iptc_profile.info; if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/354 CWE ID: CWE-415 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: gsicc_set_device_profile_colorants(gx_device *dev, char *name_str) { int code; cmm_dev_profile_t *profile_struct; gsicc_colorname_t *name_entry; gsicc_colorname_t **curr_entry; gs_memory_t *mem; char *temp_ptr, *last = NULL; int done; gsicc_namelist_t *spot_names; char *pch; int str_len; int k; bool free_str = false; code = dev_proc(dev, get_profile)((gx_device *)dev, &profile_struct); if (profile_struct != NULL) { int count = 0; if (name_str == NULL) { /* Create a default name string that we can use */ int total_len; int kk; int num_comps = profile_struct->device_profile[0]->num_comps; char temp_str[DEFAULT_ICC_COLORANT_LENGTH+2]; /* If names are already set then we do not want to set default ones */ if (profile_struct->spotnames != NULL) return 0; free_str = true; /* Assume first 4 are CMYK */ total_len = ((DEFAULT_ICC_COLORANT_LENGTH + 1) * (num_comps-4)) + DEFAULT_ICC_PROCESS_LENGTH - 1; /* -1 due to no comma at end */ name_str = (char*) gs_alloc_bytes(dev->memory, total_len+1, "gsicc_set_device_profile_colorants"); if (name_str == NULL) return gs_throw(gs_error_VMerror, "Insufficient memory for colorant name"); gs_sprintf(name_str, DEFAULT_ICC_PROCESS); for (kk = 0; kk < num_comps-5; kk++) { gs_sprintf(temp_str,"ICC_COLOR_%d,",kk); strcat(name_str,temp_str); } /* Last one no comma */ gs_sprintf(temp_str,"ICC_COLOR_%d",kk); strcat(name_str,temp_str); } str_len = strlen(name_str); if (profile_struct->spotnames != NULL && profile_struct->spotnames->name_str != NULL && strlen(profile_struct->spotnames->name_str) == str_len) { /* Here we check if the names are the same */ if (strncmp(name_str, profile_struct->spotnames->name_str, str_len) == 0) { if (free_str) gs_free_object(dev->memory, name_str, "gsicc_set_device_profile_colorants"); return 0; } } mem = dev->memory->non_gc_memory; /* We need to free the existing one if there was one */ if (profile_struct->spotnames != NULL) { /* Free the linked list in this object */ gsicc_free_spotnames(profile_struct->spotnames, mem); /* Free the main object */ gs_free_object(mem, profile_struct->spotnames, "gsicc_set_device_profile_colorants"); } /* Allocate structure for managing names */ spot_names = gsicc_new_namelist(mem); profile_struct->spotnames = spot_names; spot_names->name_str = (char*) gs_alloc_bytes(mem, str_len+1, "gsicc_set_device_profile_colorants"); if (spot_names->name_str == NULL) return gs_throw(gs_error_VMerror, "Insufficient memory for spot name"); memcpy(spot_names->name_str, name_str, strlen(name_str)); spot_names->name_str[str_len] = 0; curr_entry = &(spot_names->head); /* Go ahead and tokenize now */ pch = gs_strtok(name_str, ",", &last); count = 0; while (pch != NULL) { temp_ptr = pch; done = 0; /* Remove any leading spaces */ while (!done) { if (*temp_ptr == 0x20) { temp_ptr++; } else { done = 1; } } /* Allocate a new name object */ name_entry = gsicc_new_colorname(mem); /* Set our current entry to this one */ *curr_entry = name_entry; name_entry->length = strlen(temp_ptr); name_entry->name = (char *) gs_alloc_bytes(mem, name_entry->length, "gsicc_set_device_profile_colorants"); if (spot_names->name_str == NULL) return gs_throw(gs_error_VMerror, "Insufficient memory for spot name"); memcpy(name_entry->name, temp_ptr, name_entry->length); /* Get the next entry location */ curr_entry = &((*curr_entry)->next); count += 1; pch = gs_strtok(NULL, ",", &last); } spot_names->count = count; /* Create the color map. Query the device to find out where these colorants are located. It is possible that the device may not be opened yet. In which case, we need to make sure that when it is opened that it checks this entry and gets itself properly initialized if it is a separation device. */ spot_names->color_map = (gs_devicen_color_map*) gs_alloc_bytes(mem, sizeof(gs_devicen_color_map), "gsicc_set_device_profile_colorants"); if (spot_names->color_map == NULL) return gs_throw(gs_error_VMerror, "Insufficient memory for spot color map"); spot_names->color_map->num_colorants = count; spot_names->color_map->num_components = count; name_entry = spot_names->head; for (k = 0; k < count; k++) { int colorant_number = (*dev_proc(dev, get_color_comp_index)) (dev, (const char *)name_entry->name, name_entry->length, SEPARATION_NAME); name_entry = name_entry->next; spot_names->color_map->color_map[k] = colorant_number; } /* We need to set the equivalent CMYK color for this colorant. This is done by faking out the update spot equivalent call with a special gs_gstate and color space that makes it seem like the spot color is a separation color space. Unfortunately, we need the graphic state to do this so we save it for later when we try to do our first mapping. We then use this flag to know if we did it yet */ spot_names->equiv_cmyk_set = false; if (free_str) gs_free_object(dev->memory, name_str, "gsicc_set_device_profile_colorants"); } return code; } 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: exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) { int number, str_len = 0; xmlChar *str = NULL, *ret = NULL, *tmp; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 2) { str = xmlXPathPopString(ctxt); str_len = xmlUTF8Strlen(str); } if (str_len == 0) { if (str != NULL) xmlFree(str); str = xmlStrdup((const xmlChar *) " "); str_len = 1; } number = (int) xmlXPathPopNumber(ctxt); if (number <= 0) { xmlXPathReturnEmptyString(ctxt); xmlFree(str); return; } while (number >= str_len) { ret = xmlStrncat(ret, str, str_len); number -= str_len; } tmp = xmlUTF8Strndup (str, number); ret = xmlStrcat(ret, tmp); if (tmp != NULL) xmlFree (tmp); xmlXPathReturnString(ctxt, ret); if (str != NULL) xmlFree(str); } 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: 1 Example 2: Code: static int scoop_init(SysBusDevice *sbd) { DeviceState *dev = DEVICE(sbd); ScoopInfo *s = SCOOP(dev); s->status = 0x02; qdev_init_gpio_out(dev, s->handler, 16); qdev_init_gpio_in(dev, scoop_gpio_set, 16); memory_region_init_io(&s->iomem, OBJECT(s), &scoop_ops, s, "scoop", 0x1000); sysbus_init_mmio(sbd, &s->iomem); return 0; } 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 int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len; int split_flag = 0, depth; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0; split_flag |= EXT4_EXT_MARK_UNINIT2; flags |= EXT4_GET_BLOCKS_PRE_IO; return ext4_split_extent(handle, inode, path, map, split_flag, flags); } Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio We assumed that at the time we call ext4_convert_unwritten_extents_endio() extent in question is fully inside [map.m_lblk, map->m_len] because it was already split during submission. But this may not be true due to a race between writeback vs fallocate. If extent in question is larger than requested we will split it again. Special precautions should being done if zeroout required because [map.m_lblk, map->m_len] already contains valid data. Signed-off-by: Dmitry Monakhov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [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: void CrosLibrary::TestApi::SetCryptohomeLibrary( CryptohomeLibrary* library, bool own) { library_->crypto_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 Target: 1 Example 2: Code: void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile( const FilePath::StringType& filepath, const std::string& output) { VLOG(0) << "Writing renderer heap profile dump to: " << filepath; file_util::WriteFile(FilePath(filepath), output.c_str(), output.size()); } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 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: static void watchdog_interrupt_count(void) { __this_cpu_inc(hrtimer_interrupts); } 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:
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 read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); } free(buffer); } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310 Target: 1 Example 2: Code: static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth) { if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth) return; size_t i = 0; for (BidiRun* r = firstRun; r; r = r->next()) { if (r->m_startsSegment) break; if (!r->m_box || r == trailingSpaceRun) continue; if (r->m_object->isText()) { unsigned opportunitiesInRun = expansionOpportunities[i++]; ASSERT(opportunitiesInRun <= expansionOpportunityCount); if (r->m_object->style()->collapseWhiteSpace()) { InlineTextBox* textBox = toInlineTextBox(r->m_box); int expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount; textBox->setExpansion(expansion); totalLogicalWidth += expansion; } expansionOpportunityCount -= opportunitiesInRun; if (!expansionOpportunityCount) break; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 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: IHEVCD_ERROR_T ihevcd_operation_point_set(vps_t *ps_vps, bitstrm_t *ps_bitstrm, WORD32 ops_idx) { WORD32 i; WORD32 value; IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; UNUSED(ops_idx); for(i = 0; i <= ps_vps->i1_vps_max_nuh_reserved_zero_layer_id; i++) { BITS_PARSE("list_entry_l0[ i ]", value, ps_bitstrm, 1); } UNUSED(value); return ret; } Commit Message: Check only allocated mv bufs for releasing from reference When checking mv bufs for releasing from reference, unallocated mv bufs were also checked. This issue was fixed by restricting the loop count to allocated number of mv bufs. Bug: 34896906 Bug: 34819017 Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb (cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2) 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: int SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_.get()) return result; if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) { const HttpNetworkSession::Params* session_params = context_->GetNetworkSessionParams(); if (session_params && session_params->ignore_certificate_errors) return OK; } if (!delegate_) return result; SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); TransportSecurityState::DomainState domain_state; const bool fatal = context_->transport_security_state() && context_->transport_security_state()->GetDomainState(url_.host(), SSLConfigService::IsSNIAvailable(context_->ssl_config_service()), &domain_state) && domain_state.ShouldSSLErrorsBeFatal(); delegate_->OnSSLCertificateError(this, ssl_info, fatal); return ERR_IO_PENDING; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: int CSSStyleSheet::addRule(const String& selector, const String& style, ExceptionState& exception_state) { return addRule(selector, style, length(), exception_state); } Commit Message: Disallow access to opaque CSS responses. Bug: 848786 Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec Reviewed-on: https://chromium-review.googlesource.com/1088335 Reviewed-by: Kouhei Ueno <[email protected]> Commit-Queue: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#565537} 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: void DesktopWindowTreeHostX11::CloseNow() { if (xwindow_ == x11::None) return; ReleaseCapture(); native_widget_delegate_->OnNativeWidgetDestroying(); std::set<DesktopWindowTreeHostX11*> window_children_copy = window_children_; for (auto it = window_children_copy.begin(); it != window_children_copy.end(); ++it) { (*it)->CloseNow(); } DCHECK(window_children_.empty()); if (window_parent_) { window_parent_->window_children_.erase(this); window_parent_ = nullptr; } desktop_native_widget_aura_->root_window_event_filter()->RemoveHandler( x11_non_client_event_filter_.get()); x11_non_client_event_filter_.reset(); DestroyCompositor(); open_windows().remove(xwindow_); if (ui::PlatformEventSource::GetInstance()) ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); XDestroyWindow(xdisplay_, xwindow_); xwindow_ = x11::None; desktop_native_widget_aura_->OnHostClosed(); } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} 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: status_t OMXNodeInstance::useGraphicBuffer( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id *buffer) { Mutex::Autolock autoLock(mLock); OMX_INDEXTYPE index; if (OMX_GetExtensionIndex( mHandle, const_cast<OMX_STRING>("OMX.google.android.index.useAndroidNativeBuffer2"), &index) == OMX_ErrorNone) { return useGraphicBuffer2_l(portIndex, graphicBuffer, buffer); } OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.useAndroidNativeBuffer"); OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err != OMX_ErrorNone) { CLOG_ERROR(getExtensionIndex, err, "%s", name); return StatusFromOMXError(err); } BufferMeta *bufferMeta = new BufferMeta(graphicBuffer); OMX_BUFFERHEADERTYPE *header; OMX_VERSIONTYPE ver; ver.s.nVersionMajor = 1; ver.s.nVersionMinor = 0; ver.s.nRevision = 0; ver.s.nStep = 0; UseAndroidNativeBufferParams params = { sizeof(UseAndroidNativeBufferParams), ver, portIndex, bufferMeta, &header, graphicBuffer, }; err = OMX_SetParameter(mHandle, index, &params); if (err != OMX_ErrorNone) { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u meta=%p GB=%p", name, index, portString(portIndex), portIndex, bufferMeta, graphicBuffer->handle); delete bufferMeta; bufferMeta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, bufferMeta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); CLOG_BUFFER(useGraphicBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "GB=%p", graphicBuffer->handle)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119 Target: 1 Example 2: Code: static void ToColor_SI8_Alpha(SkColor dst[], const void* src, int width, SkColorTable* ctable) { SkASSERT(width > 0); const uint8_t* s = (const uint8_t*)src; const SkPMColor* colors = ctable->lockColors(); do { *dst++ = SkUnPreMultiply::PMColorToColor(colors[*s++]); } while (--width != 0); ctable->unlockColors(); } Commit Message: Make Bitmap_createFromParcel check the color count. DO NOT MERGE When reading from the parcel, if the number of colors is invalid, early exit. Add two more checks: setInfo must return true, and Parcel::readInplace must return non-NULL. The former ensures that the previously read values (width, height, etc) were valid, and the latter checks that the Parcel had enough data even if the number of colors was reasonable. Also use an auto-deleter to handle deletion of the SkBitmap. Cherry pick from change-Id: Icbd562d6d1f131a723724883fd31822d337cf5a6 BUG=19666945 Change-Id: Iab0d218c41ae0c39606e333e44cda078eef32291 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: static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/348 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_slice(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_slice_vertical_position; UWORD32 u4_slice_vertical_position_extension; IMPEG2D_ERROR_CODES_T e_error; ps_stream = &ps_dec->s_bit_stream; /*------------------------------------------------------------------------*/ /* All the profiles supported require restricted slice structure. Hence */ /* there is no need to store slice_vertical_position. Note that max */ /* height supported does not exceed 2800 and scalablity is not supported */ /*------------------------------------------------------------------------*/ /* Remove the slice start code */ impeg2d_bit_stream_flush(ps_stream,START_CODE_PREFIX_LEN); u4_slice_vertical_position = impeg2d_bit_stream_get(ps_stream, 8); if(u4_slice_vertical_position > 2800) { u4_slice_vertical_position_extension = impeg2d_bit_stream_get(ps_stream, 3); u4_slice_vertical_position += (u4_slice_vertical_position_extension << 7); } if((u4_slice_vertical_position > ps_dec->u2_num_vert_mb) || (u4_slice_vertical_position == 0)) { return IMPEG2D_INVALID_VERT_SIZE; } u4_slice_vertical_position--; if (ps_dec->u2_mb_y != u4_slice_vertical_position) { ps_dec->u2_mb_y = u4_slice_vertical_position; ps_dec->u2_mb_x = 0; } ps_dec->u2_first_mb = 1; /*------------------------------------------------------------------------*/ /* Quant scale code decoding */ /*------------------------------------------------------------------------*/ { UWORD16 u2_quant_scale_code; u2_quant_scale_code = impeg2d_bit_stream_get(ps_stream,5); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); } if (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); /* Flush extra bit information */ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); } } impeg2d_bit_stream_get_bit(ps_stream); /* Reset the DC predictors to reset values given in Table 7.2 at the start*/ /* of slice data */ ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; /*------------------------------------------------------------------------*/ /* dec->DecMBsinSlice() implements the following psuedo code from standard*/ /* do */ /* { */ /* macroblock() */ /* } while (impeg2d_bit_stream_nxt() != '000 0000 0000 0000 0000 0000') */ /*------------------------------------------------------------------------*/ e_error = ps_dec->pf_decode_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } /* Check for the MBy index instead of number of MBs left, because the * number of MBs left in case of multi-thread decode is the number of MBs * in that row only */ if(ps_dec->u2_mb_y < ps_dec->u2_num_vert_mb) impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Target: 1 Example 2: Code: static void VoidMethodDefaultNullableStringArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::ToImpl(info.Holder()); V8StringResource<kTreatNullAndUndefinedAsNullString> default_string_arg; if (!info[0]->IsUndefined()) { default_string_arg = info[0]; if (!default_string_arg.Prepare()) return; } else { default_string_arg = nullptr; } impl->voidMethodDefaultNullableStringArg(default_string_arg); } 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 SyncBackendHost::HandleSyncCycleCompletedOnFrontendLoop( const SyncSessionSnapshot& snapshot) { if (!frontend_) return; DCHECK_EQ(MessageLoop::current(), frontend_loop_); last_snapshot_ = snapshot; SDVLOG(1) << "Got snapshot " << snapshot.ToString(); const syncable::ModelTypeSet to_migrate = snapshot.syncer_status().types_needing_local_migration; if (!to_migrate.Empty()) frontend_->OnMigrationNeededForTypes(to_migrate); if (initialized()) AddExperimentalTypes(); if (pending_download_state_.get()) { const syncable::ModelTypeSet types_to_add = pending_download_state_->types_to_add; const syncable::ModelTypeSet added_types = pending_download_state_->added_types; DCHECK(types_to_add.HasAll(added_types)); const syncable::ModelTypeSet initial_sync_ended = snapshot.initial_sync_ended(); const syncable::ModelTypeSet failed_configuration_types = Difference(added_types, initial_sync_ended); SDVLOG(1) << "Added types: " << syncable::ModelTypeSetToString(added_types) << ", configured types: " << syncable::ModelTypeSetToString(initial_sync_ended) << ", failed configuration types: " << syncable::ModelTypeSetToString(failed_configuration_types); if (!failed_configuration_types.Empty() && snapshot.retry_scheduled()) { if (!pending_download_state_->retry_in_progress) { pending_download_state_->retry_callback.Run(); pending_download_state_->retry_in_progress = true; } return; } scoped_ptr<PendingConfigureDataTypesState> state( pending_download_state_.release()); state->ready_task.Run(failed_configuration_types); if (!failed_configuration_types.Empty()) return; } if (initialized()) frontend_->OnSyncCycleCompleted(); } 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 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 ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec) { if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; return 0; } Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw() the only non-trivial detail is that we do it before rw_verify_area(), so we'd better cap the length ourselves in aio_setup_single_rw() case (for vectored case rw_copy_check_uvector() will do that for us). Signed-off-by: Al Viro <[email protected]> CWE ID: Target: 1 Example 2: Code: mm_answer_gss_accept_ctx(int sock, Buffer *m) { gss_buffer_desc in; gss_buffer_desc out = GSS_C_EMPTY_BUFFER; OM_uint32 major, minor; OM_uint32 flags = 0; /* GSI needs this */ u_int len; in.value = buffer_get_string(m, &len); in.length = len; major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags); free(in.value); buffer_clear(m); buffer_put_int(m, major); buffer_put_string(m, out.value, out.length); buffer_put_int(m, flags); mm_request_send(sock, MONITOR_ANS_GSSSTEP, m); gss_release_buffer(&minor, &out); if (major == GSS_S_COMPLETE) { monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0); monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1); monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1); } return (0); } Commit Message: set sshpam_ctxt to NULL after free Avoids use-after-free in monitor when privsep child is compromised. Reported by Moritz Jodeit; ok dtucker@ 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: static int aio_setup_ring(struct kioctx *ctx) { struct aio_ring *ring; struct aio_ring_info *info = &ctx->ring_info; unsigned nr_events = ctx->max_reqs; unsigned long size; int nr_pages; /* Compensate for the ring buffer's head/tail overlap entry */ nr_events += 2; /* 1 is required, 2 for good luck */ size = sizeof(struct aio_ring); size += sizeof(struct io_event) * nr_events; nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT; if (nr_pages < 0) return -EINVAL; nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event); info->nr = 0; info->ring_pages = info->internal_pages; if (nr_pages > AIO_RING_PAGES) { info->ring_pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!info->ring_pages) return -ENOMEM; } info->mmap_size = nr_pages * PAGE_SIZE; dprintk("attempting mmap of %lu bytes\n", info->mmap_size); down_write(&ctx->mm->mmap_sem); info->mmap_base = do_mmap(NULL, 0, info->mmap_size, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, 0); if (IS_ERR((void *)info->mmap_base)) { up_write(&ctx->mm->mmap_sem); info->mmap_size = 0; aio_free_ring(ctx); return -EAGAIN; } dprintk("mmap address: 0x%08lx\n", info->mmap_base); info->nr_pages = get_user_pages(current, ctx->mm, info->mmap_base, nr_pages, 1, 0, info->ring_pages, NULL); up_write(&ctx->mm->mmap_sem); if (unlikely(info->nr_pages != nr_pages)) { aio_free_ring(ctx); return -EAGAIN; } ctx->user_id = info->mmap_base; info->nr = nr_events; /* trusted copy */ ring = kmap_atomic(info->ring_pages[0], KM_USER0); ring->nr = nr_events; /* user copy */ ring->id = ctx->user_id; ring->head = ring->tail = 0; ring->magic = AIO_RING_MAGIC; ring->compat_features = AIO_RING_COMPAT_FEATURES; ring->incompat_features = AIO_RING_INCOMPAT_FEATURES; ring->header_length = sizeof(struct aio_ring); kunmap_atomic(ring, KM_USER0); return 0; } Commit Message: Unused iocbs in a batch should not be accounted as active. commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream. Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are allocated in a batch during processing of first iocbs. All iocbs in a batch are automatically added to ctx->active_reqs list and accounted in ctx->reqs_active. If one (not the last one) of iocbs submitted by an user fails, further iocbs are not processed, but they are still present in ctx->active_reqs and accounted in ctx->reqs_active. This causes process to stuck in a D state in wait_for_all_aios() on exit since ctx->reqs_active will never go down to zero. Furthermore since kiocb_batch_free() frees iocb without removing it from active_reqs list the list become corrupted which may cause oops. Fix this by removing iocb from ctx->active_reqs and updating ctx->reqs_active in kiocb_batch_free(). Signed-off-by: Gleb Natapov <[email protected]> Reviewed-by: Jeff Moyer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> 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 BluetoothDeviceChromeOS::UnregisterAgent() { if (!agent_.get()) return; DCHECK(pairing_delegate_); DCHECK(pincode_callback_.is_null()); DCHECK(passkey_callback_.is_null()); DCHECK(confirmation_callback_.is_null()); pairing_delegate_->DismissDisplayOrConfirm(); pairing_delegate_ = NULL; agent_.reset(); VLOG(1) << object_path_.value() << ": Unregistering pairing agent"; DBusThreadManager::Get()->GetBluetoothAgentManagerClient()-> UnregisterAgent( dbus::ObjectPath(kAgentPath), base::Bind(&base::DoNothing), base::Bind(&BluetoothDeviceChromeOS::OnUnregisterAgentError, weak_ptr_factory_.GetWeakPtr())); } 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 ValidateRendererAllocations(base::Value* dump_json) { SCOPED_TRACE("Validating Renderer Allocation"); base::ProcessId renderer_pid = base::GetProcId(browser() ->tab_strip_model() ->GetActiveWebContents() ->GetMainFrame() ->GetProcess() ->GetHandle()); base::Value* heaps_v2 = FindHeapsV2(renderer_pid, dump_json); if (GetParam() == switches::kMemlogModeAll || GetParam() == switches::kMemlogModeRendererSampling) { ASSERT_TRUE(heaps_v2); } else { ASSERT_FALSE(heaps_v2) << "There should be no heap dump for the renderer."; } if (GetParam() == switches::kMemlogModeRendererSampling) { EXPECT_EQ(1, NumProcessesWithName(dump_json, "Renderer")); } else { EXPECT_GT(NumProcessesWithName(dump_json, "Renderer"), 0); } } Commit Message: [Reland #1] Add Android OOP HP end-to-end tests. The original CL added a javatest and its dependencies to the apk_under_test. This causes the dependencies to be stripped from the instrumentation_apk, which causes issue. This CL updates the build configuration so that the javatest and its dependencies are only added to the instrumentation_apk. This is a reland of e0b4355f0651adb1ebc2c513dc4410471af712f5 Original change's description: > Add Android OOP HP end-to-end tests. > > This CL has three components: > 1) The bulk of the logic in OOP HP was refactored into ProfilingTestDriver. > 2) Adds a java instrumentation test, along with a JNI shim that forwards into > ProfilingTestDriver. > 3) Creates a new apk: chrome_public_apk_for_test that contains the same > content as chrome_public_apk, as well as native files needed for (2). > chrome_public_apk_test now targets chrome_public_apk_for_test instead of > chrome_public_apk. > > Other ideas, discarded: > * Originally, I attempted to make the browser_tests target runnable on > Android. The primary problem is that native test harness cannot fork > or spawn processes. This is difficult to solve. > > More details on each of the components: > (1) ProfilingTestDriver > * The TracingController test was migrated to use ProfilingTestDriver, but the > write-to-file test was left as-is. The latter behavior will likely be phased > out, but I'll clean that up in a future CL. > * gtest isn't supported for Android instrumentation tests. ProfilingTestDriver > has a single function RunTest that returns a 'bool' indicating success. On > failure, the class uses LOG(ERROR) to print the nature of the error. This will > cause the error to be printed out on browser_test error. On instrumentation > test failure, the error will be forwarded to logcat, which is available on all > infra bot test runs. > (2) Instrumentation test > * For now, I only added a single test for the "browser" mode. Furthermore, I'm > only testing the start with command-line path. > (3) New apk > * libchromefortest is a new shared library that contains all content from > libchrome, but also contains native sources for the JNI shim. > * chrome_public_apk_for_test is a new apk that contains all content from > chrome_public_apk, but uses a single shared library libchromefortest rather > than libchrome. This also contains java sources for the JNI shim. > * There is no way to just add a second shared library to chrome_public_apk > that just contains the native sources from the JNI shim without causing ODR > issues. > * chrome_public_test_apk now has apk_under_test = chrome_public_apk_for_test. > * There is no way to add native JNI sources as a shared library to > chrome_public_test_apk without causing ODR issues. > > Finally, this CL drastically increases the timeout to wait for native > initialization. The previous timeout was 2 * > CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL, which flakily failed for this test. > This suggests that this step/timeout is generally flaky. I increased the timeout > to 20 * CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL. > > Bug: 753218 > Change-Id: Ic224b7314fff57f1770a4048aa5753f54e040b55 > Reviewed-on: https://chromium-review.googlesource.com/770148 > Commit-Queue: Erik Chen <[email protected]> > Reviewed-by: John Budorick <[email protected]> > Reviewed-by: Brett Wilson <[email protected]> > Cr-Commit-Position: refs/heads/master@{#517541} Bug: 753218 TBR: [email protected] Change-Id: Ic6aafb34c2467253f75cc85da48200d19f3bc9af Reviewed-on: https://chromium-review.googlesource.com/777697 Commit-Queue: Erik Chen <[email protected]> Reviewed-by: John Budorick <[email protected]> Cr-Commit-Position: refs/heads/master@{#517850} 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: cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, "parent inode = 0x%p name is: %s and dentry = 0x%p", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow "/", but "\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\') { cFYI(1, "Invalid file name"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, "non-NULL inode in lookup"); } else { cFYI(1, "NULL inode in lookup"); } cFYI(1, "Full path: %s inode = 0x%p", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ if ((rc == 0) || (rc == -ENOENT)) posix_open = true; else if ((rc == -EINVAL) || (rc != -EOPNOTSUPP)) pTcon->broken_posix_open = true; } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, "Unexpected lookup error %d", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); } Commit Message: cifs: fix dentry refcount leak when opening a FIFO on lookup commit 5bccda0ebc7c0331b81ac47d39e4b920b198b2cd upstream. The cifs code will attempt to open files on lookup under certain circumstances. What happens though if we find that the file we opened was actually a FIFO or other special file? Currently, the open filehandle just ends up being leaked leading to a dentry refcount mismatch and oops on umount. Fix this by having the code close the filehandle on the server if it turns out not to be a regular file. While we're at it, change this spaghetti if statement into a switch too. Reported-by: CAI Qian <[email protected]> Tested-by: CAI Qian <[email protected]> Reviewed-by: Shirish Pargaonkar <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/ Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static int __btrfs_correct_data_nocsum(struct inode *inode, struct btrfs_io_bio *io_bio) { struct bio_vec *bvec; struct btrfs_retry_complete done; u64 start; int i; int ret; start = io_bio->logical; done.inode = inode; bio_for_each_segment_all(bvec, &io_bio->bio, i) { try_again: done.uptodate = 0; done.start = start; init_completion(&done.done); ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start, start + bvec->bv_len - 1, io_bio->mirror_num, btrfs_retry_endio_nocsum, &done); if (ret) return ret; wait_for_completion(&done.done); if (!done.uptodate) { /* We might have another mirror, so try again */ goto try_again; } start += bvec->bv_len; } return 0; } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[email protected]> 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 svc_rdma_init(void) { dprintk("SVCRDMA Module Init, register RPC RDMA transport\n"); dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord); dprintk("\tmax_requests : %u\n", svcrdma_max_requests); dprintk("\tsq_depth : %u\n", svcrdma_max_requests * RPCRDMA_SQ_DEPTH_MULT); dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests); dprintk("\tmax_inline : %d\n", svcrdma_max_req_size); svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0); if (!svc_rdma_wq) return -ENOMEM; if (!svcrdma_table_header) svcrdma_table_header = register_sysctl_table(svcrdma_root_table); /* Register RDMA with the SVC transport switch */ svc_reg_xprt_class(&svc_rdma_class); #if defined(CONFIG_SUNRPC_BACKCHANNEL) svc_reg_xprt_class(&svc_rdma_bc_class); #endif return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 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 VRDisplay::ProcessScheduledWindowAnimations(double timestamp) { TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_); auto doc = navigator_vr_->GetDocument(); if (!doc) return; auto page = doc->GetPage(); if (!page) return; page->Animator().ServiceScriptedAnimations(timestamp); } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID: Target: 1 Example 2: Code: static GuestFileHandle *guest_file_handle_find(int64_t id, Error **err) { GuestFileHandle *gfh; QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) { if (gfh->id == id) { return gfh; } } error_setg(err, "handle '%" PRId64 "' has not been found", id); return NULL; } 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: static int ocfs2_dio_end_io_write(struct inode *inode, struct ocfs2_dio_write_ctxt *dwc, loff_t offset, ssize_t bytes) { struct ocfs2_cached_dealloc_ctxt dealloc; struct ocfs2_extent_tree et; struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_unwritten_extent *ue = NULL; struct buffer_head *di_bh = NULL; struct ocfs2_dinode *di; struct ocfs2_alloc_context *data_ac = NULL; struct ocfs2_alloc_context *meta_ac = NULL; handle_t *handle = NULL; loff_t end = offset + bytes; int ret = 0, credits = 0, locked = 0; ocfs2_init_dealloc_ctxt(&dealloc); /* We do clear unwritten, delete orphan, change i_size here. If neither * of these happen, we can skip all this. */ if (list_empty(&dwc->dw_zero_list) && end <= i_size_read(inode) && !dwc->dw_orphaned) goto out; /* ocfs2_file_write_iter will get i_mutex, so we need not lock if we * are in that context. */ if (dwc->dw_writer_pid != task_pid_nr(current)) { inode_lock(inode); locked = 1; } ret = ocfs2_inode_lock(inode, &di_bh, 1); if (ret < 0) { mlog_errno(ret); goto out; } down_write(&oi->ip_alloc_sem); /* Delete orphan before acquire i_mutex. */ if (dwc->dw_orphaned) { BUG_ON(dwc->dw_writer_pid != task_pid_nr(current)); end = end > i_size_read(inode) ? end : 0; ret = ocfs2_del_inode_from_orphan(osb, inode, di_bh, !!end, end); if (ret < 0) mlog_errno(ret); } di = (struct ocfs2_dinode *)di_bh->b_data; ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh); ret = ocfs2_lock_allocators(inode, &et, 0, dwc->dw_zero_count*2, &data_ac, &meta_ac); if (ret) { mlog_errno(ret); goto unlock; } credits = ocfs2_calc_extend_credits(inode->i_sb, &di->id2.i_list); handle = ocfs2_start_trans(osb, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); mlog_errno(ret); goto unlock; } ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh, OCFS2_JOURNAL_ACCESS_WRITE); if (ret) { mlog_errno(ret); goto commit; } list_for_each_entry(ue, &dwc->dw_zero_list, ue_node) { ret = ocfs2_mark_extent_written(inode, &et, handle, ue->ue_cpos, 1, ue->ue_phys, meta_ac, &dealloc); if (ret < 0) { mlog_errno(ret); break; } } if (end > i_size_read(inode)) { ret = ocfs2_set_inode_size(handle, inode, di_bh, end); if (ret < 0) mlog_errno(ret); } commit: ocfs2_commit_trans(osb, handle); unlock: up_write(&oi->ip_alloc_sem); ocfs2_inode_unlock(inode, 1); brelse(di_bh); out: if (data_ac) ocfs2_free_alloc_context(data_ac); if (meta_ac) ocfs2_free_alloc_context(meta_ac); ocfs2_run_deallocs(osb, &dealloc); if (locked) inode_unlock(inode); ocfs2_dio_free_write_ctx(inode, dwc); return ret; } Commit Message: ocfs2: ip_alloc_sem should be taken in ocfs2_get_block() ip_alloc_sem should be taken in ocfs2_get_block() when reading file in DIRECT mode to prevent concurrent access to extent tree with ocfs2_dio_end_io_write(), which may cause BUGON in the following situation: read file 'A' end_io of writing file 'A' vfs_read __vfs_read ocfs2_file_read_iter generic_file_read_iter ocfs2_direct_IO __blockdev_direct_IO do_blockdev_direct_IO do_direct_IO get_more_blocks ocfs2_get_block ocfs2_extent_map_get_blocks ocfs2_get_clusters ocfs2_get_clusters_nocache() ocfs2_search_extent_list return the index of record which contains the v_cluster, that is v_cluster > rec[i]->e_cpos. ocfs2_dio_end_io ocfs2_dio_end_io_write down_write(&oi->ip_alloc_sem); ocfs2_mark_extent_written ocfs2_change_extent_flag ocfs2_split_extent ... --> modify the rec[i]->e_cpos, resulting in v_cluster < rec[i]->e_cpos. BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos)) [[email protected]: v3] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io") Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Reviewed-by: Gang He <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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: struct sock *inet_csk_clone_lock(const struct sock *sk, const struct request_sock *req, const gfp_t priority) { struct sock *newsk = sk_clone_lock(sk, priority); if (newsk) { struct inet_connection_sock *newicsk = inet_csk(newsk); newsk->sk_state = TCP_SYN_RECV; newicsk->icsk_bind_hash = NULL; inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port; inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num; inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num); newsk->sk_write_space = sk_stream_write_space; /* listeners have SOCK_RCU_FREE, not the children */ sock_reset_flag(newsk, SOCK_RCU_FREE); newsk->sk_mark = inet_rsk(req)->ir_mark; atomic64_set(&newsk->sk_cookie, atomic64_read(&inet_rsk(req)->ir_cookie)); newicsk->icsk_retransmits = 0; newicsk->icsk_backoff = 0; newicsk->icsk_probes_out = 0; /* Deinitialize accept_queue to trap illegal accesses. */ memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue)); security_inet_csk_clone(newsk, req); } return newsk; } Commit Message: dccp/tcp: do not inherit mc_list from parent syzkaller found a way to trigger double frees from ip_mc_drop_socket() It turns out that leave a copy of parent mc_list at accept() time, which is very bad. Very similar to commit 8b485ce69876 ("tcp: do not inherit fastopen_req from parent") Initial report from Pray3r, completed by Andrey one. Thanks a lot to them ! Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Pray3r <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-415 Target: 1 Example 2: Code: const char *string_of_NPError(int error) { const char *str; switch ((NPError)error) { #define _(VAL) case VAL: str = #VAL; break; _(NPERR_NO_ERROR); _(NPERR_GENERIC_ERROR); _(NPERR_INVALID_INSTANCE_ERROR); _(NPERR_INVALID_FUNCTABLE_ERROR); _(NPERR_MODULE_LOAD_FAILED_ERROR); _(NPERR_OUT_OF_MEMORY_ERROR); _(NPERR_INVALID_PLUGIN_ERROR); _(NPERR_INVALID_PLUGIN_DIR_ERROR); _(NPERR_INCOMPATIBLE_VERSION_ERROR); _(NPERR_INVALID_PARAM); _(NPERR_INVALID_URL); _(NPERR_FILE_NOT_FOUND); _(NPERR_NO_DATA); _(NPERR_STREAM_NOT_SEEKABLE); #undef _ default: str = "<unknown error>"; break; } return str; } Commit Message: Support all the new variables added 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: main (int argc _GL_UNUSED, char **argv) { struct timespec result; struct timespec result2; struct timespec expected; struct timespec now; const char *p; int i; long gmtoff; time_t ref_time = 1304250918; /* Set the time zone to US Eastern time with the 2012 rules. This should disable any leap second support. Otherwise, there will be a problem with glibc on sites that default to leap seconds; see <http://bugs.gnu.org/12206>. */ setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1); gmtoff = gmt_offset (ref_time); /* ISO 8601 extended date and time of day representation, 'T' separator, local time zone */ p = "2011-05-01T11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, local time zone */ p = "2011-05-01 11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, 'T' separator, UTC */ p = "2011-05-01T11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, ' ' separator, UTC */ p = "2011-05-01 11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/UTC offset */ p = "2011-05-01T11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/UTC offset */ p = "2011-05-01 11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/hour only UTC offset */ p = "2011-05-01T11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/hour only UTC offset */ p = "2011-05-01 11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "4 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); /* test if timezone is not being ignored for day offset */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 +24 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* test if several time zones formats are handled same way */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC-1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+0:15"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+0015"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-1:30"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-130"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* TZ out of range should cause parse_datetime failure */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+25:00"; ASSERT (!parse_datetime (&result, p, &now)); /* Check for several invalid countable dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+4:00 +40 yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 next yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow hence"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 40 now ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 last tomorrow"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 -4 today"; ASSERT (!parse_datetime (&result, p, &now)); /* And check correct usage of dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+400 1 day hence"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 1 day ago"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/ ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* Check that some "next Monday", "last Wednesday", etc. are correct. */ setenv ("TZ", "UTC0", 1); for (i = 0; day_table[i]; i++) { unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */ char tmp[32]; sprintf (tmp, "NEXT %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600); sprintf (tmp, "LAST %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600); } p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */ now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == now.tv_sec && result.tv_nsec == now.tv_nsec); p = "FRIDAY UTC+00"; now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == 24 * 3600 && result.tv_nsec == now.tv_nsec); /* Exercise a sign-extension bug. Before July 2012, an input starting with a high-bit-set byte would be treated like "0". */ ASSERT ( ! parse_datetime (&result, "\xb0", &now)); /* Exercise TZ="" parsing code. */ /* These two would infloop or segfault before Feb 2014. */ ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now)); /* Exercise invalid patterns. */ ASSERT ( ! parse_datetime (&result, "TZ=\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now)); /* Exercise valid patterns. */ ASSERT ( parse_datetime (&result, "TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now)); ASSERT ( parse_datetime (&result, " TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now)); return 0; } 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 Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, index, *redmap; MagickBooleanType explicit_file, explicit_retry, polarity, sequence, use_explicit; MagickOffsetType offset; Quantum *scale; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bits_allocated, bytes_per_pixel, colors, depth, height, length, mask, max_value, number_scenes, quantum, samples_per_pixel, signed_data, significant_bits, status, width, window_width; ssize_t count, rescale_intercept, rescale_slope, scene, window_center, y; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent); bits_allocated=8; bytes_per_pixel=1; polarity=MagickFalse; data=(unsigned char *) NULL; depth=8; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; max_value=255UL; mask=0xffff; number_scenes=1; rescale_intercept=0; rescale_slope=1; samples_per_pixel=1; scale=(Quantum *) NULL; sequence=MagickFalse; signed_data=(~0UL); significant_bits=0; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; window_center=0; window_width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"UL",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"FL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype); if (count < 1) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ bits_allocated=(size_t) datum; bytes_per_pixel=1; if (datum > 8) bytes_per_pixel=2; depth=bits_allocated; if (depth > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); max_value=(1UL << bits_allocated)-1; break; } case 0x0101: { /* Bits stored. */ significant_bits=(size_t) datum; bytes_per_pixel=1; if (significant_bits > 8) bytes_per_pixel=2; depth=significant_bits; if (depth > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); max_value=(1UL << significant_bits)-1; mask=(size_t) GetQuantumRange(significant_bits); break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) window_center=(ssize_t) StringToLong((char *) data); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) window_width=StringToUnsignedLong((char *) data); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) rescale_intercept=(ssize_t) StringToLong((char *) data); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) rescale_slope=(ssize_t) StringToLong((char *) data); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) colors; i++) if (bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data,exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (signed_data == 0xffff) signed_data=(size_t) (significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MagickPathExtent, "jpeg:%s",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, "j2k:%s",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(depth)+1); scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale)); if (scale == (Quantum *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); range=GetQuantumRange(depth); for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++) scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1)) { size_t one; one=1; if (colors == 0) colors=one << depth; if (AcquireImageColormap(image,one << depth,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); if (stream_info->segment_count > 1) { bytes_per_pixel=1; depth=8; } for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; } if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; int byte; PixelPacket pixel; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; if ((window_center != 0) && (window_width == 0)) window_width=(size_t) window_center; option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) window_width=0; } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { if (signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=ReadDCMShort(stream_info,image); if (polarity != MagickFalse) pixel_value=(int)max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) index,q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) pixel.red,q); SetPixelGreen(image,(Quantum) pixel.green,q); SetPixelBlue(image,(Quantum) pixel.blue,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (stream_info->segment_count > 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { pixel_value=(int) (polarity != MagickFalse ? (max_value-ReadDCMShort(stream_info,image)) : ReadDCMShort(stream_info,image)); if (signed_data == 1) pixel_value=((signed short) pixel_value); } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) (((size_t) GetPixelIndex(image,q)) | (((size_t) index) << 8)),q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) | (((size_t) pixel.red) << 8)),q); SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) | (((size_t) pixel.green) << 8)),q); SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) | (((size_t) pixel.blue) << 8)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (scale != (Quantum *) NULL) scale=(Quantum *) RelinquishMagickMemory(scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Add additional checks to DCM reader to prevent data-driven faults (bug report from Hanno Böck CWE ID: CWE-20 Target: 1 Example 2: Code: int oidc_auth_checker(request_rec *r) { /* check for anonymous access and PASS mode */ if (r->user != NULL && strlen(r->user) == 0) { r->user = NULL; if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS) return OK; } /* get the set of claims from the request state (they've been set in the authentication part earlier */ json_t *claims = NULL, *id_token = NULL; oidc_authz_get_claims_and_idtoken(r, &claims, &id_token); /* get the Require statements */ const apr_array_header_t * const reqs_arr = ap_requires(r); /* see if we have any */ const require_line * const reqs = reqs_arr ? (require_line *) reqs_arr->elts : NULL; if (!reqs_arr) { oidc_debug(r, "no require statements found, so declining to perform authorization."); return DECLINED; } /* merge id_token claims (e.g. "iss") in to claims json object */ if (claims) oidc_util_json_merge(r, id_token, claims); /* dispatch to the <2.4 specific authz routine */ int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs, reqs_arr->nelts); /* cleanup */ if (claims) json_decref(claims); if (id_token) json_decref(id_token); if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r)) rc = oidc_handle_unauthorized_user22(r); return rc; } Commit Message: release 2.3.10.2: fix XSS vulnerability for poll parameter in OIDC Session Management RP iframe; CSNC-2019-001; thanks Mischa Bachmann Signed-off-by: Hans Zandbelt <[email protected]> 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: ProxyChannelDelegate::~ProxyChannelDelegate() { } 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: void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; if (p->mm) { /* adjust to KB unit */ stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB; } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; } Commit Message: [PATCH] xacct_add_tsk: fix pure theoretical ->mm use-after-free Paranoid fix. The task can free its ->mm after the 'if (p->mm)' check. Signed-off-by: Oleg Nesterov <[email protected]> Cc: Shailabh Nagar <[email protected]> Cc: Balbir Singh <[email protected]> Cc: Jay Lan <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: void* Type_ColorantTable_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n) { cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr; return (void*) cmsDupNamedColorList(nc); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug 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 * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; int contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, "authorization", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, "basic", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){ sb = buf + 15; while(isspace(*sb))sb++; contentlen = atoi(sb); } else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n"); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, "<tr>" "<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>", (cp->comment)?cp->comment:"&nbsp;", (cp->disabled)?'S':'D', num, (cp->disabled)?"NO":"YES" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n"); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, "</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n" ); } else { inbuf += sprintf(buf+inbuf, "</td><td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>MB%s</td>" "<td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>%s</td>", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):"never" ); inbuf += sprintf(buf + inbuf, "<td>%s</td>" "<td>%i</td>" "</tr>\r\n", cp->updated?ctime(&cp->updated):"never", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, "<h3>Reload scheduled</h3>"); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>"); break; } printstr(&pp, "<h3>Please be careful editing config file remotely</h3>"); printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">"); while(fgets(buf, 256, fp)){ printstr(&pp, buf); } if(!writable) fclose(fp); printstr(&pp, "</textarea><br><input type=\"Submit\"></form>"); break; } case 'U': { int l=0; int error = 0; if(!writable || fseek(writable, 0, 0)){ error = 1; } while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); buf[i] = 0; if(!l){ if(strncasecmp(buf, "conffile=", 9)) error = 1; } if(!error){ decodeurl((unsigned char *)buf, 1); fprintf(writable, "%s", l? buf : buf + 9); } l += i; if(l >= contentlen) break; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file": "<h3>Configuration updated</h3>"); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); } Commit Message: Fix: out-of-bounds write and few more bugs in 'admin' configuration upload 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: updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; } Commit Message: updateDevice() remove element from the list when realloc fails CWE ID: CWE-416 Target: 1 Example 2: Code: explicit FactoryForExtensions(const ProfileIOData* profile_io_data) : profile_io_data_(profile_io_data) {} Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 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: void testAnimatedWithClear() { m_testSurface->initializeCurrentFrame(); m_testSurface->getPicture(); m_testSurface->willOverwriteCanvas(); m_fakeImageBufferClient->fakeDraw(); EXPECT_EQ(1, m_fakeImageBufferClient->frameCount()); m_testSurface->getPicture(); EXPECT_EQ(2, m_fakeImageBufferClient->frameCount()); expectDisplayListEnabled(true); m_fakeImageBufferClient->fakeDraw(); m_testSurface->willOverwriteCanvas(); EXPECT_EQ(2, m_fakeImageBufferClient->frameCount()); m_testSurface->getPicture(); EXPECT_EQ(3, m_fakeImageBufferClient->frameCount()); expectDisplayListEnabled(true); } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310 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: cib_recv_plaintext(int sock) { char *buf = NULL; ssize_t rc = 0; ssize_t len = 0; ssize_t chunk_size = 512; buf = calloc(1, chunk_size); while (1) { errno = 0; rc = read(sock, buf + len, chunk_size); crm_trace("Got %d more bytes. errno=%d", (int)rc, errno); if (errno == EINTR || errno == EAGAIN) { crm_trace("Retry: %d", (int)rc); if (rc > 0) { len += rc; buf = realloc(buf, len + chunk_size); CRM_ASSERT(buf != NULL); } } else if (rc < 0) { crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc); goto bail; } else if (rc == chunk_size) { len += rc; chunk_size *= 2; buf = realloc(buf, len + chunk_size); crm_trace("Retry with %d more bytes", (int)chunk_size); CRM_ASSERT(buf != NULL); } else if (buf[len + rc - 1] != 0) { crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]); crm_trace("Retry with %d more bytes", (int)chunk_size); len += rc; buf = realloc(buf, len + chunk_size); CRM_ASSERT(buf != NULL); } else { return buf; } } bail: free(buf); return NULL; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Target: 1 Example 2: Code: void ImageLoader::setImage(ImageResourceContent* newImage) { setImageWithoutConsideringPendingLoadEvent(newImage); updatedHasPendingEvent(); } Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer. Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer. This associates it with the frame's Networking timer task queue. BUG=624694 Review-Url: https://codereview.chromium.org/2642103002 Cr-Commit-Position: refs/heads/master@{#444927} 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: nfsd4_encode_commit(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_commit *commit) { struct xdr_stream *xdr = &resp->xdr; __be32 *p; if (!nfserr) { p = xdr_reserve_space(xdr, NFS4_VERIFIER_SIZE); if (!p) return nfserr_resource; p = xdr_encode_opaque_fixed(p, commit->co_verf.data, NFS4_VERIFIER_SIZE); } return nfserr; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 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 SetUp() { video_ = new libvpx_test::WebMVideoSource(kVP9TestFile); ASSERT_TRUE(video_ != NULL); video_->Init(); video_->Begin(); vpx_codec_dec_cfg_t cfg = {0}; decoder_ = new libvpx_test::VP9Decoder(cfg, 0); ASSERT_TRUE(decoder_ != NULL); } 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: MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info, const MagickBooleanType split,TypeMetric *metrics,char **caption, ExceptionInfo *exception) { MagickBooleanType status; register char *p, *q, *s; register ssize_t i; size_t width; ssize_t n; q=draw_info->text; s=(char *) NULL; for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p)) { if (IsUTFSpace(GetUTFCode(p)) != MagickFalse) s=p; if (GetUTFCode(p) == '\n') { q=draw_info->text; continue; } for (i=0; i < (ssize_t) GetUTFOctets(p); i++) *q++=(*(p+i)); *q='\0'; status=GetTypeMetrics(image,draw_info,metrics,exception); if (status == MagickFalse) break; width=(size_t) floor(metrics->width+draw_info->stroke_width+0.5); if (width <= image->columns) continue; if (s != (char *) NULL) { *s='\n'; p=s; } else if (split != MagickFalse) { /* No convenient line breaks-- insert newline. */ n=p-(*caption); if ((n > 0) && ((*caption)[n-1] != '\n')) { char *target; target=AcquireString(*caption); CopyMagickString(target,*caption,n+1); ConcatenateMagickString(target,"\n",strlen(*caption)+1); ConcatenateMagickString(target,p,strlen(*caption)+2); (void) DestroyString(*caption); *caption=target; p=(*caption)+n; } } q=draw_info->text; s=(char *) NULL; } n=0; for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p)) if (GetUTFCode(p) == '\n') n++; return(n); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1589 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: CCThreadProxy::CCThreadProxy(CCLayerTreeHost* layerTreeHost) : m_commitRequested(false) , m_layerTreeHost(layerTreeHost) , m_compositorIdentifier(-1) , m_started(false) , m_lastExecutedBeginFrameAndCommitSequenceNumber(-1) , m_numBeginFrameAndCommitsIssuedOnCCThread(0) { TRACE_EVENT("CCThreadProxy::CCThreadProxy", this, 0); ASSERT(isMainThread()); } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 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: compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb) { png_uint_32 x; for (x=0; x<width; ++x) { png_byte bval = ppb[x]; png_byte aval = ppa[x]; if (bval > bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; y<height; ++y, rowa += stridea, rowb += strideb) { png_const_bytep ppa, ppb; png_uint_32 x; for (x=0, ppa=rowa, ppb=rowb; x<width; ++x) { png_const_bytep psa, psb; if (formata & PNG_FORMAT_FLAG_COLORMAP) psa = (png_const_bytep)a->colormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; } 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: bool RenderThreadImpl::IsDistanceFieldTextEnabled() { return is_distance_field_text_enabled_; } Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6 https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604 BUG=778101 Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c Reviewed-on: https://chromium-review.googlesource.com/747941 Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: David Benjamin <[email protected]> Commit-Queue: Steven Valdez <[email protected]> Cr-Commit-Position: refs/heads/master@{#513774} CWE ID: CWE-310 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 ieee80211_radiotap_iterator_init( struct ieee80211_radiotap_iterator *iterator, struct ieee80211_radiotap_header *radiotap_header, int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns) { /* Linux only supports version 0 radiotap format */ if (radiotap_header->it_version) return -EINVAL; /* sanity check for allowed length and radiotap length field */ if (max_length < get_unaligned_le16(&radiotap_header->it_len)) return -EINVAL; iterator->_rtheader = radiotap_header; iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len); iterator->_arg_index = 0; iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present); iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header); iterator->_reset_on_ext = 0; iterator->_next_bitmap = &radiotap_header->it_present; iterator->_next_bitmap++; iterator->_vns = vns; iterator->current_namespace = &radiotap_ns; iterator->is_radiotap_ns = 1; /* find payload start allowing for extended bitmap(s) */ if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) { while (get_unaligned_le32(iterator->_arg) & (1 << IEEE80211_RADIOTAP_EXT)) { iterator->_arg += sizeof(uint32_t); /* * check for insanity where the present bitmaps * keep claiming to extend up to or even beyond the * stated radiotap header length */ if ((unsigned long)iterator->_arg - (unsigned long)iterator->_rtheader > (unsigned long)iterator->_max_length) return -EINVAL; } iterator->_arg += sizeof(uint32_t); /* * no need to check again for blowing past stated radiotap * header length, because ieee80211_radiotap_iterator_next * checks it before it is dereferenced */ } iterator->this_arg = iterator->_arg; /* we are all initialized happily */ return 0; } Commit Message: wireless: radiotap: fix parsing buffer overrun When parsing an invalid radiotap header, the parser can overrun the buffer that is passed in because it doesn't correctly check 1) the minimum radiotap header size 2) the space for extended bitmaps The first issue doesn't affect any in-kernel user as they all check the minimum size before calling the radiotap function. The second issue could potentially affect the kernel if an skb is passed in that consists only of the radiotap header with a lot of extended bitmaps that extend past the SKB. In that case a read-only buffer overrun by at most 4 bytes is possible. Fix this by adding the appropriate checks to the parser. Cc: [email protected] Reported-by: Evan Huus <[email protected]> Signed-off-by: Johannes Berg <[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: bool Chapters::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_size = size; return true; } 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: read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); } 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: static inline int pfkey_init_proc(struct net *net) { return 0; } Commit Message: af_key: initialize satype in key_notify_policy_flush() This field was left uninitialized. Some user daemons perform check against this field. Signed-off-by: Nicolas Dichtel <[email protected]> Signed-off-by: Steffen Klassert <[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 BiquadDSPKernel::process(const float* source, float* destination, size_t framesToProcess) { ASSERT(source && destination && biquadProcessor()); updateCoefficientsIfNecessary(true, false); m_biquad.process(source, destination, framesToProcess); } Commit Message: Initialize value since calculateFinalValues may fail to do so. Fix threading issue where updateCoefficientsIfNecessary was not always called from the audio thread. This causes the value not to be initialized. Thus, o Initialize the variable to some value, just in case. o Split updateCoefficientsIfNecessary into two functions with the code that sets the coefficients pulled out in to the new function updateCoefficients. o Simplify updateCoefficientsIfNecessary since useSmoothing was always true, and forceUpdate is not longer needed. o Add process lock to prevent the audio thread from updating the coefficients while they are being read in the main thread. The audio thread will update them the next time around. o Make getFrequencyResponse set the lock while reading the coefficients of the biquad in preparation for computing the frequency response. BUG=389219 Review URL: https://codereview.chromium.org/354213002 git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static int rndis_parse(USBNetState *s, uint8_t *data, int length) { uint32_t msg_type; le32 *tmp = (le32 *) data; msg_type = le32_to_cpup(tmp); switch (msg_type) { case RNDIS_INITIALIZE_MSG: s->rndis_state = RNDIS_INITIALIZED; return rndis_init_response(s, (rndis_init_msg_type *) data); case RNDIS_HALT_MSG: s->rndis_state = RNDIS_UNINITIALIZED; return 0; case RNDIS_QUERY_MSG: return rndis_query_response(s, (rndis_query_msg_type *) data, length); case RNDIS_SET_MSG: return rndis_set_response(s, (rndis_set_msg_type *) data, length); case RNDIS_RESET_MSG: rndis_clear_responsequeue(s); s->out_ptr = 0; usb_net_reset_in_buf(s); return rndis_reset_response(s, (rndis_reset_msg_type *) data); case RNDIS_KEEPALIVE_MSG: /* For USB: host does this every 5 seconds */ return rndis_keepalive_response(s, (rndis_keepalive_msg_type *) data); } return USB_RET_STALL; } 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: int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads, unsigned count) { int start, n, r; start = vq->last_used_idx % vq->num; n = vq->num - start; if (n < count) { r = __vhost_add_used_n(vq, heads, n); if (r < 0) return r; heads += n; count -= n; } r = __vhost_add_used_n(vq, heads, count); /* Make sure buffer is written before we update index. */ smp_wmb(); if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) { vq_err(vq, "Failed to increment used idx"); return -EFAULT; } if (unlikely(vq->log_used)) { /* Log used index update. */ log_write(vq->log_base, vq->log_addr + offsetof(struct vring_used, idx), sizeof vq->used->idx); if (vq->log_ctx) eventfd_signal(vq->log_ctx, 1); } return r; } Commit Message: vhost: actually track log eventfd file While reviewing vhost log code, I found out that log_file is never set. Note: I haven't tested the change (QEMU doesn't use LOG_FD yet). Cc: [email protected] Signed-off-by: Marc-André Lureau <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> 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 PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_NE(NOT_PREVIEWING, print_preview_state_); if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125 Target: 1 Example 2: Code: static void key_garbage_collector(struct work_struct *work) { static LIST_HEAD(graveyard); static u8 gc_state; /* Internal persistent state */ #define KEY_GC_REAP_AGAIN 0x01 /* - Need another cycle */ #define KEY_GC_REAPING_LINKS 0x02 /* - We need to reap links */ #define KEY_GC_SET_TIMER 0x04 /* - We need to restart the timer */ #define KEY_GC_REAPING_DEAD_1 0x10 /* - We need to mark dead keys */ #define KEY_GC_REAPING_DEAD_2 0x20 /* - We need to reap dead key links */ #define KEY_GC_REAPING_DEAD_3 0x40 /* - We need to reap dead keys */ #define KEY_GC_FOUND_DEAD_KEY 0x80 /* - We found at least one dead key */ struct rb_node *cursor; struct key *key; time_t new_timer, limit; kenter("[%lx,%x]", key_gc_flags, gc_state); limit = current_kernel_time().tv_sec; if (limit > key_gc_delay) limit -= key_gc_delay; else limit = key_gc_delay; /* Work out what we're going to be doing in this pass */ gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2; gc_state <<= 1; if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags)) gc_state |= KEY_GC_REAPING_LINKS | KEY_GC_SET_TIMER; if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) gc_state |= KEY_GC_REAPING_DEAD_1; kdebug("new pass %x", gc_state); new_timer = LONG_MAX; /* As only this function is permitted to remove things from the key * serial tree, if cursor is non-NULL then it will always point to a * valid node in the tree - even if lock got dropped. */ spin_lock(&key_serial_lock); cursor = rb_first(&key_serial_tree); continue_scanning: while (cursor) { key = rb_entry(cursor, struct key, serial_node); cursor = rb_next(cursor); if (atomic_read(&key->usage) == 0) goto found_unreferenced_key; if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) { if (key->type == key_gc_dead_keytype) { gc_state |= KEY_GC_FOUND_DEAD_KEY; set_bit(KEY_FLAG_DEAD, &key->flags); key->perm = 0; goto skip_dead_key; } } if (gc_state & KEY_GC_SET_TIMER) { if (key->expiry > limit && key->expiry < new_timer) { kdebug("will expire %x in %ld", key_serial(key), key->expiry - limit); new_timer = key->expiry; } } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) if (key->type == key_gc_dead_keytype) gc_state |= KEY_GC_FOUND_DEAD_KEY; if ((gc_state & KEY_GC_REAPING_LINKS) || unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) { if (key->type == &key_type_keyring) goto found_keyring; } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) if (key->type == key_gc_dead_keytype) goto destroy_dead_key; skip_dead_key: if (spin_is_contended(&key_serial_lock) || need_resched()) goto contended; } contended: spin_unlock(&key_serial_lock); maybe_resched: if (cursor) { cond_resched(); spin_lock(&key_serial_lock); goto continue_scanning; } /* We've completed the pass. Set the timer if we need to and queue a * new cycle if necessary. We keep executing cycles until we find one * where we didn't reap any keys. */ kdebug("pass complete"); if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) { new_timer += key_gc_delay; key_schedule_gc(new_timer); } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) || !list_empty(&graveyard)) { /* Make sure that all pending keyring payload destructions are * fulfilled and that people aren't now looking at dead or * dying keys that they don't have a reference upon or a link * to. */ kdebug("gc sync"); synchronize_rcu(); } if (!list_empty(&graveyard)) { kdebug("gc keys"); key_gc_unused_keys(&graveyard); } if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2))) { if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) { /* No remaining dead keys: short circuit the remaining * keytype reap cycles. */ kdebug("dead short"); gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2); gc_state |= KEY_GC_REAPING_DEAD_3; } else { gc_state |= KEY_GC_REAP_AGAIN; } } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) { kdebug("dead wake"); smp_mb(); clear_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags); wake_up_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE); } if (gc_state & KEY_GC_REAP_AGAIN) schedule_work(&key_gc_work); kleave(" [end %x]", gc_state); return; /* We found an unreferenced key - once we've removed it from the tree, * we can safely drop the lock. */ found_unreferenced_key: kdebug("unrefd key %d", key->serial); rb_erase(&key->serial_node, &key_serial_tree); spin_unlock(&key_serial_lock); list_add_tail(&key->graveyard_link, &graveyard); gc_state |= KEY_GC_REAP_AGAIN; goto maybe_resched; /* We found a keyring and we need to check the payload for links to * dead or expired keys. We don't flag another reap immediately as we * have to wait for the old payload to be destroyed by RCU before we * can reap the keys to which it refers. */ found_keyring: spin_unlock(&key_serial_lock); keyring_gc(key, limit); goto maybe_resched; /* We found a dead key that is still referenced. Reset its type and * destroy its payload with its semaphore held. */ destroy_dead_key: spin_unlock(&key_serial_lock); kdebug("destroy key %d", key->serial); down_write(&key->sem); key->type = &key_type_dead; if (key_gc_dead_keytype->destroy) key_gc_dead_keytype->destroy(key); memset(&key->payload, KEY_DESTROY, sizeof(key->payload)); up_write(&key->sem); goto maybe_resched; } Commit Message: Merge branch 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs Pull key handling fixes from David Howells: "Here are two patches, the first of which at least should go upstream immediately: (1) Prevent a user-triggerable crash in the keyrings destructor when a negatively instantiated keyring is garbage collected. I have also seen this triggered for user type keys. (2) Prevent the user from using requesting that a keyring be created and instantiated through an upcall. Doing so is probably safe since the keyring type ignores the arguments to its instantiation function - but we probably shouldn't let keyrings be created in this manner" * 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs: KEYS: Don't permit request_key() to construct a new keyring KEYS: Fix crash when attempt to garbage collect an uninstantiated keyring 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 UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas, const cc::PaintFlags& flags, const FloatRect& dst_rect, const FloatRect& src_rect, RespectImageOrientationEnum, ImageClampingMode clamp_mode, ImageDecodingMode) { StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode, PaintImageForCurrentFrame()); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} 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: virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods()); return descriptors->size(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int slabstats_open(struct inode *inode, struct file *file) { unsigned long *n; n = __seq_open_private(file, &slabstats_op, PAGE_SIZE); if (!n) return -ENOMEM; *n = PAGE_SIZE / (2 * sizeof(unsigned long)); return 0; } Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries This patch fixes a bug in the freelist randomization code. When a high random number is used, the freelist will contain duplicate entries. It will result in different allocations sharing the same chunk. It will result in odd behaviours and crashes. It should be uncommon but it depends on the machines. We saw it happening more often on some machines (every few hours of running tests). Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: John Sperbeck <[email protected]> Signed-off-by: Thomas Garnier <[email protected]> Cc: Christoph Lameter <[email protected]> Cc: Pekka Enberg <[email protected]> Cc: David Rientjes <[email protected]> Cc: Joonsoo Kim <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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 vmci_transport_set_buffer_size(struct vsock_sock *vsk, u64 val) { if (val < vmci_trans(vsk)->queue_pair_min_size) vmci_trans(vsk)->queue_pair_min_size = val; if (val > vmci_trans(vsk)->queue_pair_max_size) vmci_trans(vsk)->queue_pair_max_size = val; vmci_trans(vsk)->queue_pair_size = val; } Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue() In case we received no data on the call to skb_recv_datagram(), i.e. skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0 without updating msg_namelen leading to net/socket.c leaking the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix this by moving the already existing msg_namelen assignment a few lines above. Cc: Andy King <[email protected]> Cc: Dmitry Torokhov <[email protected]> Cc: George Zhang <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartcol; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartcol = (numrows + 1 - parity) >> 1; m = numrows - hstartcol; /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += JPC_QMFB_COLGRPSIZE; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartcol * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += JPC_QMFB_COLGRPSIZE; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119 Target: 1 Example 2: Code: void tcp_free_fastopen_req(struct tcp_sock *tp) { if (tp->fastopen_req) { kfree(tp->fastopen_req); tp->fastopen_req = NULL; } } Commit Message: tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0 When tcp_disconnect() is called, inet_csk_delack_init() sets icsk->icsk_ack.rcv_mss to 0. This could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() => __tcp_select_window() call path to have division by 0 issue. So this patch initializes rcv_mss to TCP_MIN_MSS instead of 0. Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Wei Wang <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Neal Cardwell <[email protected]> Signed-off-by: Yuchung Cheng <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 MediaStreamManager::StopDevice(MediaStreamType type, int session_id) { DVLOG(1) << "StopDevice" << "{type = " << type << "}" << "{session_id = " << session_id << "}"; DeviceRequests::iterator request_it = requests_.begin(); while (request_it != requests_.end()) { DeviceRequest* request = request_it->second; MediaStreamDevices* devices = &request->devices; if (devices->empty()) { ++request_it; continue; } MediaStreamDevices::iterator device_it = devices->begin(); while (device_it != devices->end()) { if (device_it->type != type || device_it->session_id != session_id) { ++device_it; continue; } if (request->state(type) == MEDIA_REQUEST_STATE_DONE) CloseDevice(type, session_id); device_it = devices->erase(device_it); } if (devices->empty()) { std::string label = request_it->first; ++request_it; DeleteRequest(label); } else { ++request_it; } } } Commit Message: Fix MediaObserver notifications in MediaStreamManager. This CL fixes the stream type used to notify MediaObserver about cancelled MediaStream requests. Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate that all stream types should be cancelled. However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this way and the request to update the UI is ignored. This CL sends a separate notification for each stream type so that the UI actually gets updated for all stream types in use. Bug: 816033 Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405 Reviewed-on: https://chromium-review.googlesource.com/939630 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#540122} 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 ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { return dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: int bdev_read_only(struct block_device *bdev) { if (!bdev) return 0; return bdev->bd_part->policy; } Commit Message: block: fix use-after-free in seq file I got a KASAN report of use-after-free: ================================================================== BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508 Read of size 8 by task trinity-c1/315 ============================================================================= BUG kmalloc-32 (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315 ___slab_alloc+0x4f1/0x520 __slab_alloc.isra.58+0x56/0x80 kmem_cache_alloc_trace+0x260/0x2a0 disk_seqf_start+0x66/0x110 traverse+0x176/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315 __slab_free+0x17a/0x2c0 kfree+0x20a/0x220 disk_seqf_stop+0x42/0x50 traverse+0x3b5/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480 ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480 ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970 Call Trace: [<ffffffff81d6ce81>] dump_stack+0x65/0x84 [<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0 [<ffffffff814704ff>] object_err+0x2f/0x40 [<ffffffff814754d1>] kasan_report_error+0x221/0x520 [<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40 [<ffffffff83888161>] klist_iter_exit+0x61/0x70 [<ffffffff82404389>] class_dev_iter_exit+0x9/0x10 [<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50 [<ffffffff8151f812>] seq_read+0x4b2/0x11a0 [<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180 [<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210 [<ffffffff814b4c45>] do_readv_writev+0x565/0x660 [<ffffffff814b8a17>] vfs_readv+0x67/0xa0 [<ffffffff814b8de6>] do_preadv+0x126/0x170 [<ffffffff814b92ec>] SyS_preadv+0xc/0x10 This problem can occur in the following situation: open() - pread() - .seq_start() - iter = kmalloc() // succeeds - seqf->private = iter - .seq_stop() - kfree(seqf->private) - pread() - .seq_start() - iter = kmalloc() // fails - .seq_stop() - class_dev_iter_exit(seqf->private) // boom! old pointer As the comment in disk_seqf_stop() says, stop is called even if start failed, so we need to reinitialise the private pointer to NULL when seq iteration stops. An alternative would be to set the private pointer to NULL when the kmalloc() in disk_seqf_start() fails. Cc: [email protected] Signed-off-by: Vegard Nossum <[email protected]> Acked-by: Tejun Heo <[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: gray_raster_render( PRaster raster, const FT_Raster_Params* params ) { const FT_Outline* outline = (const FT_Outline*)params->source; const FT_Bitmap* target_map = params->target; PWorker worker; if ( !raster || !raster->buffer || !raster->buffer_size ) return ErrRaster_Invalid_Argument; if ( !outline ) return ErrRaster_Invalid_Outline; /* return immediately if the outline is empty */ if ( outline->n_points == 0 || outline->n_contours <= 0 ) return 0; if ( !outline->contours || !outline->points ) return ErrRaster_Invalid_Outline; if ( outline->n_points != outline->contours[outline->n_contours - 1] + 1 ) return ErrRaster_Invalid_Outline; worker = raster->worker; /* if direct mode is not set, we must have a target bitmap */ if ( !( params->flags & FT_RASTER_FLAG_DIRECT ) ) { if ( !target_map ) return ErrRaster_Invalid_Argument; /* nothing to do */ if ( !target_map->width || !target_map->rows ) return 0; if ( !target_map->buffer ) return ErrRaster_Invalid_Argument; } /* this version does not support monochrome rendering */ if ( !( params->flags & FT_RASTER_FLAG_AA ) ) return ErrRaster_Invalid_Mode; /* compute clipping box */ if ( !( params->flags & FT_RASTER_FLAG_DIRECT ) ) { /* compute clip box from target pixmap */ ras.clip_box.xMin = 0; ras.clip_box.yMin = 0; ras.clip_box.xMax = target_map->width; ras.clip_box.yMax = target_map->rows; } else if ( params->flags & FT_RASTER_FLAG_CLIP ) ras.clip_box = params->clip_box; else { ras.clip_box.xMin = -32768L; ras.clip_box.yMin = -32768L; ras.clip_box.xMax = 32767L; ras.clip_box.yMax = 32767L; } gray_init_cells( RAS_VAR_ raster->buffer, raster->buffer_size ); ras.outline = *outline; ras.num_cells = 0; ras.invalid = 1; ras.band_size = raster->band_size; ras.num_gray_spans = 0; if ( params->flags & FT_RASTER_FLAG_DIRECT ) { ras.render_span = (FT_Raster_Span_Func)params->gray_spans; ras.render_span_data = params->user; } else { ras.target = *target_map; ras.render_span = (FT_Raster_Span_Func)gray_render_span; ras.render_span_data = &ras; } return gray_convert_glyph( RAS_VAR ); } Commit Message: 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: static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int len; if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) { rfcomm_dlc_accept(d); return 0; } len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags); lock_sock(sk); if (!(flags & MSG_PEEK) && len > 0) atomic_sub(len, &sk->sk_rmem_alloc); if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2)) rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc); release_sock(sk); return len; } Commit Message: Bluetooth: RFCOMM - Fix missing msg_namelen update in rfcomm_sock_recvmsg() If RFCOMM_DEFER_SETUP is set in the flags, rfcomm_sock_recvmsg() returns early with 0 without updating the possibly set msg_namelen member. This, in turn, leads to a 128 byte kernel stack leak in net/socket.c. Fix this by updating msg_namelen in this case. For all other cases it will be handled in bt_sock_stream_recvmsg(). Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void Document::addListenerTypeIfNeeded(const AtomicString& eventType) { if (eventType == EventTypeNames::DOMSubtreeModified) { UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent); addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER); } else if (eventType == EventTypeNames::DOMNodeInserted) { UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent); addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER); } else if (eventType == EventTypeNames::DOMNodeRemoved) { UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent); addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER); } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) { UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent); addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER); } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) { UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent); addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER); } else if (eventType == EventTypeNames::DOMCharacterDataModified) { UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent); addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER); } else if (eventType == EventTypeNames::overflowchanged && RuntimeEnabledFeatures::overflowChangedEventEnabled()) { UseCounter::countDeprecation(*this, UseCounter::OverflowChangedEvent); addListenerType(OVERFLOWCHANGED_LISTENER); } else if (eventType == EventTypeNames::webkitAnimationStart || eventType == EventTypeNames::animationstart) { addListenerType(ANIMATIONSTART_LISTENER); } else if (eventType == EventTypeNames::webkitAnimationEnd || eventType == EventTypeNames::animationend) { addListenerType(ANIMATIONEND_LISTENER); } else if (eventType == EventTypeNames::webkitAnimationIteration || eventType == EventTypeNames::animationiteration) { addListenerType(ANIMATIONITERATION_LISTENER); if (view()) { view()->scheduleAnimation(); } } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) { addListenerType(TRANSITIONEND_LISTENER); } else if (eventType == EventTypeNames::scroll) { addListenerType(SCROLL_LISTENER); } } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg, X509_ALGOR **pmaskHash) { const unsigned char *p; int plen; RSA_PSS_PARAMS *pss; *pmaskHash = NULL; if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen); if (!pss) return NULL; if (pss->maskGenAlgorithm) { ASN1_TYPE *param = pss->maskGenAlgorithm->parameter; if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1 && param->type == V_ASN1_SEQUENCE) { p = param->value.sequence->data; plen = param->value.sequence->length; *pmaskHash = d2i_X509_ALGOR(NULL, &p, plen); } } return pss; } Commit Message: 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: static void kvmclock_reset(struct kvm_vcpu *vcpu) { if (vcpu->arch.time_page) { kvm_release_page_dirty(vcpu->arch.time_page); vcpu->arch.time_page = NULL; } } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: int floadAlice(void *clientData, uint8_t **output, uint32_t *size, zrtpFreeBuffer_callback *cb) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *ALICECACHE = fopen(filename, "r+"); fseek(ALICECACHE, 0L, SEEK_END); /* Position to end of file */ *size = ftell(ALICECACHE); /* Get file length */ rewind(ALICECACHE); /* Back to start of file */ *output = (uint8_t *)malloc(*size*sizeof(uint8_t)+1); if (fread(*output, 1, *size, ALICECACHE)==0){ fprintf(stderr,"floadAlice() fread() error\n"); } *(*output+*size) = '\0'; *size += 1; fclose(ALICECACHE); *cb=freeBuf; return *size; } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception 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: static void scsi_free_request(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); qemu_vfree(r->iov.iov_base); } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[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: void TabletModeWindowManager::Init() { { ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this, /*exiting_tablet_mode=*/false); ArrangeWindowsForTabletMode(); } AddWindowCreationObservers(); display::Screen::GetScreen()->AddObserver(this); Shell::Get()->AddShellObserver(this); Shell::Get()->session_controller()->AddObserver(this); Shell::Get()->overview_controller()->AddObserver(this); accounts_since_entering_tablet_.insert( Shell::Get()->session_controller()->GetActiveAccountId()); event_handler_ = std::make_unique<wm::TabletModeEventHandler>(); } Commit Message: Fix the crash after clamshell -> tablet transition in overview mode. This CL just reverted some changes that were made in https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In that CL, we changed the clamshell <-> tablet transition when clamshell split view mode is enabled, however, we should keep the old behavior unchanged if the feature is not enabled, i.e., overview should be ended if it's active before the transition. Otherwise, it will cause a nullptr dereference crash since |split_view_drag_indicators_| is not created in clamshell overview and will be used in tablet overview. Bug: 982507 Change-Id: I238fe9472648a446cff4ab992150658c228714dd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]> Cr-Commit-Position: refs/heads/master@{#679306} CWE ID: CWE-362 Target: 1 Example 2: Code: void InspectorClientImpl::highlight() { if (WebDevToolsAgentImpl* agent = devToolsAgent()) agent->highlight(); } 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: void sctp_generate_proto_unreach_event(unsigned long data) { struct sctp_transport *transport = (struct sctp_transport *) data; struct sctp_association *asoc = transport->asoc; struct net *net = sock_net(asoc->base.sk); bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy\n", __func__); /* Try again later. */ if (!mod_timer(&transport->proto_unreach_timer, jiffies + (HZ/20))) sctp_association_hold(asoc); goto out_unlock; } /* Is this structure just waiting around for us to actually * get destroyed? */ if (asoc->base.dead) goto out_unlock; sctp_do_sm(net, SCTP_EVENT_T_OTHER, SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH), asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC); 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 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 ssize_t qib_write(struct file *fp, const char __user *data, size_t count, loff_t *off) { const struct qib_cmd __user *ucmd; struct qib_ctxtdata *rcd; const void __user *src; size_t consumed, copy = 0; struct qib_cmd cmd; ssize_t ret = 0; void *dest; if (count < sizeof(cmd.type)) { ret = -EINVAL; goto bail; } ucmd = (const struct qib_cmd __user *) data; if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) { ret = -EFAULT; goto bail; } consumed = sizeof(cmd.type); switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: case QIB_CMD_USER_INIT: copy = sizeof(cmd.cmd.user_info); dest = &cmd.cmd.user_info; src = &ucmd->cmd.user_info; break; case QIB_CMD_RECV_CTRL: copy = sizeof(cmd.cmd.recv_ctrl); dest = &cmd.cmd.recv_ctrl; src = &ucmd->cmd.recv_ctrl; break; case QIB_CMD_CTXT_INFO: copy = sizeof(cmd.cmd.ctxt_info); dest = &cmd.cmd.ctxt_info; src = &ucmd->cmd.ctxt_info; break; case QIB_CMD_TID_UPDATE: case QIB_CMD_TID_FREE: copy = sizeof(cmd.cmd.tid_info); dest = &cmd.cmd.tid_info; src = &ucmd->cmd.tid_info; break; case QIB_CMD_SET_PART_KEY: copy = sizeof(cmd.cmd.part_key); dest = &cmd.cmd.part_key; src = &ucmd->cmd.part_key; break; case QIB_CMD_DISARM_BUFS: case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */ copy = 0; src = NULL; dest = NULL; break; case QIB_CMD_POLL_TYPE: copy = sizeof(cmd.cmd.poll_type); dest = &cmd.cmd.poll_type; src = &ucmd->cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: copy = sizeof(cmd.cmd.armlaunch_ctrl); dest = &cmd.cmd.armlaunch_ctrl; src = &ucmd->cmd.armlaunch_ctrl; break; case QIB_CMD_SDMA_INFLIGHT: copy = sizeof(cmd.cmd.sdma_inflight); dest = &cmd.cmd.sdma_inflight; src = &ucmd->cmd.sdma_inflight; break; case QIB_CMD_SDMA_COMPLETE: copy = sizeof(cmd.cmd.sdma_complete); dest = &cmd.cmd.sdma_complete; src = &ucmd->cmd.sdma_complete; break; case QIB_CMD_ACK_EVENT: copy = sizeof(cmd.cmd.event_mask); dest = &cmd.cmd.event_mask; src = &ucmd->cmd.event_mask; break; default: ret = -EINVAL; goto bail; } if (copy) { if ((count - consumed) < copy) { ret = -EINVAL; goto bail; } if (copy_from_user(dest, src, copy)) { ret = -EFAULT; goto bail; } consumed += copy; } rcd = ctxt_fp(fp); if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) { ret = -EINVAL; goto bail; } switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: ret = qib_assign_ctxt(fp, &cmd.cmd.user_info); if (ret) goto bail; break; case QIB_CMD_USER_INIT: ret = qib_do_user_init(fp, &cmd.cmd.user_info); if (ret) goto bail; ret = qib_get_base_info(fp, (void __user *) (unsigned long) cmd.cmd.user_info.spu_base_info, cmd.cmd.user_info.spu_base_info_size); break; case QIB_CMD_RECV_CTRL: ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl); break; case QIB_CMD_CTXT_INFO: ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *) (unsigned long) cmd.cmd.ctxt_info); break; case QIB_CMD_TID_UPDATE: ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info); break; case QIB_CMD_TID_FREE: ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info); break; case QIB_CMD_SET_PART_KEY: ret = qib_set_part_key(rcd, cmd.cmd.part_key); break; case QIB_CMD_DISARM_BUFS: (void)qib_disarm_piobufs_ifneeded(rcd); ret = disarm_req_delay(rcd); break; case QIB_CMD_PIOAVAILUPD: qib_force_pio_avail_update(rcd->dd); break; case QIB_CMD_POLL_TYPE: rcd->poll_type = cmd.cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl); break; case QIB_CMD_SDMA_INFLIGHT: ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_inflight); break; case QIB_CMD_SDMA_COMPLETE: ret = qib_sdma_get_complete(rcd->ppd, user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_complete); break; case QIB_CMD_ACK_EVENT: ret = qib_user_event_ack(rcd, subctxt_fp(fp), cmd.cmd.event_mask); break; } if (ret >= 0) ret = consumed; bail: return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: cmsBool WriteOffsetArray(cmsIOHANDLER* io, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length) { cmsUInt32Number i; for (i=0; i < Count; i++) { if (!WriteOneElem(io, &a -> Name, i)) return FALSE; if (!WriteOneElem(io, &a -> Value, i)) return FALSE; if (Length > 16) { if (!WriteOneElem(io, &a -> DisplayName, i)) return FALSE; } if (Length > 24) { if (!WriteOneElem(io, &a -> DisplayValue, i)) return FALSE; } } return TRUE; } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug 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: t42_parse_sfnts( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Memory memory = parser->root.memory; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Error error; FT_Int num_tables = 0; FT_ULong count, ttf_size = 0; FT_Long n, string_size, old_string_size, real_size; FT_Byte* string_buf = NULL; FT_Bool allocated = 0; T42_Load_Status status; /* The format is */ /* */ /* /sfnts [ <hexstring> <hexstring> ... ] def */ /* */ /* or */ /* */ /* /sfnts [ */ /* <num_bin_bytes> RD <binary data> */ /* <num_bin_bytes> RD <binary data> */ /* ... */ /* ] def */ /* */ /* with exactly one space after the `RD' token. */ T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit || *parser->root.cursor++ != '[' ) { FT_ERROR(( "t42_parse_sfnts: can't find begin of sfnts vector\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_Spaces( parser ); status = BEFORE_START; string_size = 0; old_string_size = 0; count = 0; while ( parser->root.cursor < limit ) { cur = parser->root.cursor; if ( *cur == ']' ) { parser->root.cursor++; goto Exit; } else if ( *cur == '<' ) { T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; /* don't include delimiters */ string_size = (FT_Long)( ( parser->root.cursor - cur - 2 + 1 ) / 2 ); if ( FT_REALLOC( string_buf, old_string_size, string_size ) ) goto Fail; allocated = 1; parser->root.cursor = cur; (void)T1_ToBytes( parser, string_buf, string_size, &real_size, 1 ); old_string_size = string_size; string_size = real_size; } else if ( ft_isdigit( *cur ) ) { if ( allocated ) { FT_ERROR(( "t42_parse_sfnts: " "can't handle mixed binary and hex strings\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } string_size = T1_ToInt( parser ); if ( string_size < 0 ) { FT_ERROR(( "t42_parse_sfnts: invalid string size\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_PS_Token( parser ); /* `RD' */ if ( parser->root.error ) return; string_buf = parser->root.cursor + 1; /* one space after `RD' */ if ( limit - parser->root.cursor < string_size ) { FT_ERROR(( "t42_parse_sfnts: too many binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } else parser->root.cursor += string_size + 1; } if ( !string_buf ) { FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* A string can have a trailing zero (odd) byte for padding. */ /* Ignore it. */ if ( ( string_size & 1 ) && string_buf[string_size - 1] == 0 ) string_size--; if ( !string_size ) { FT_ERROR(( "t42_parse_sfnts: invalid string\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } for ( n = 0; n < string_size; n++ ) { switch ( status ) { case BEFORE_START: /* load offset table, 12 bytes */ if ( count < 12 ) { face->ttf_data[count++] = string_buf[n]; continue; } else { num_tables = 16 * face->ttf_data[4] + face->ttf_data[5]; status = BEFORE_TABLE_DIR; ttf_size = 12 + 16 * num_tables; if ( FT_REALLOC( face->ttf_data, 12, ttf_size ) ) goto Fail; } /* fall through */ case BEFORE_TABLE_DIR: /* the offset table is read; read the table directory */ if ( count < ttf_size ) { face->ttf_data[count++] = string_buf[n]; continue; } else { int i; FT_ULong len; for ( i = 0; i < num_tables; i++ ) { FT_Byte* p = face->ttf_data + 12 + 16 * i + 12; len = FT_PEEK_ULONG( p ); /* Pad to a 4-byte boundary length */ ttf_size += ( len + 3 ) & ~3; } status = OTHER_TABLES; face->ttf_size = ttf_size; /* there are no more than 256 tables, so no size check here */ if ( FT_REALLOC( face->ttf_data, 12 + 16 * num_tables, ttf_size + 1 ) ) goto Fail; } /* fall through */ case OTHER_TABLES: /* all other tables are just copied */ if ( count >= ttf_size ) { FT_ERROR(( "t42_parse_sfnts: too many binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } } face->ttf_data[count++] = string_buf[n]; } } T1_Skip_Spaces( parser ); } Commit Message: 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: static int cuse_channel_release(struct inode *inode, struct file *file) { struct fuse_dev *fud = file->private_data; struct cuse_conn *cc = fc_to_cc(fud->fc); int rc; /* remove from the conntbl, no more access from this point on */ mutex_lock(&cuse_lock); list_del_init(&cc->list); mutex_unlock(&cuse_lock); /* remove device */ if (cc->dev) device_unregister(cc->dev); if (cc->cdev) { unregister_chrdev_region(cc->cdev->dev, 1); cdev_del(cc->cdev); } rc = fuse_dev_release(inode, file); /* puts the base reference */ return rc; } Commit Message: cuse: fix memory leak The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc, and the original ref count is never dropped. Reported-by: Colin Ian King <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure") Cc: <[email protected]> # v4.2+ CWE ID: CWE-399 Target: 1 Example 2: Code: static int sysvipc_sem_proc_show(struct seq_file *s, void *it) { struct user_namespace *user_ns = seq_user_ns(s); struct sem_array *sma = it; return seq_printf(s, "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n", sma->sem_perm.key, sma->sem_perm.id, sma->sem_perm.mode, sma->sem_nsems, from_kuid_munged(user_ns, sma->sem_perm.uid), from_kgid_munged(user_ns, sma->sem_perm.gid), from_kuid_munged(user_ns, sma->sem_perm.cuid), from_kgid_munged(user_ns, sma->sem_perm.cgid), sma->sem_otime, sma->sem_ctime); } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: bool GLES2DecoderImpl::SimulateFixedAttribs( const char* function_name, GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_->HaveFixedAttribs()) { return true; } PerformanceWarning( "GL_FIXED attributes have a signficant performance penalty"); GLuint elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_->GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { GLuint elements_used = 0; if (!SafeMultiply(num_vertices, static_cast<GLuint>(info->size()), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } } const GLuint kSizeOfFloat = sizeof(float); // NOLINT GLuint size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array<float> data(new float[size]); const int32* src = reinterpret_cast<const int32 *>( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast<float>(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast<GLvoid*>(offset)); offset += size; } } *simulated = true; return true; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 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: static void MSLStartElement(void *context,const xmlChar *tag, const xmlChar **attributes) { AffineMatrix affine, current; ChannelType channel; char key[MaxTextExtent], *value; const char *attribute, *keyword; double angle; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; int flags; ssize_t option, j, n, x, y; MSLInfo *msl_info; RectangleInfo geometry; register ssize_t i; size_t height, width; /* Called when an opening tag has been processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startElement(%s",tag); exception=AcquireExceptionInfo(); msl_info=(MSLInfo *) context; n=msl_info->n; keyword=(const char *) NULL; value=(char *) NULL; SetGeometryInfo(&geometry_info); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); channel=DefaultChannels; switch (*tag) { case 'A': case 'a': { if (LocaleCompare((const char *) tag,"add-noise") == 0) { Image *noise_image; NoiseType noise; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } noise=UniformNoise; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'N': case 'n': { if (LocaleCompare(keyword,"noise") == 0) { option=ParseCommandOption(MagickNoiseOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); noise=(NoiseType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } noise_image=AddNoiseImageChannel(msl_info->image[n],channel,noise, &msl_info->image[n]->exception); if (noise_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=noise_image; break; } if (LocaleCompare((const char *) tag,"annotate") == 0) { char text[MaxTextExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value,&draw_info->fill, exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorDatabase(value,&draw_info->stroke, exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorDatabase(value,&draw_info->undercolor, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) AnnotateImage(msl_info->image[n],draw_info); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"append") == 0) { Image *append_image; MagickBooleanType stack; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } stack=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"stack") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); stack=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } append_image=AppendImages(msl_info->image[n],stack, &msl_info->image[n]->exception); if (append_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=append_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } case 'B': case 'b': { if (LocaleCompare((const char *) tag,"blur") == 0) { Image *blur_image; /* Blur image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } blur_image=BlurImageChannel(msl_info->image[n],channel, geometry_info.rho,geometry_info.sigma, &msl_info->image[n]->exception); if (blur_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=blur_image; break; } if (LocaleCompare((const char *) tag,"border") == 0) { Image *border_image; /* Border image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value, &msl_info->image[n]->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } border_image=BorderImage(msl_info->image[n],&geometry, &msl_info->image[n]->exception); if (border_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=border_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'C': case 'c': { if (LocaleCompare((const char *) tag,"colorize") == 0) { char opacity[MaxTextExtent]; Image *colorize_image; PixelPacket target; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } target=msl_info->image[n]->background_color; (void) CopyMagickString(opacity,"100",MaxTextExtent); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorDatabase(value,&target, &msl_info->image[n]->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { (void) CopyMagickString(opacity,value,MaxTextExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } colorize_image=ColorizeImage(msl_info->image[n],opacity,target, &msl_info->image[n]->exception); if (colorize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=colorize_image; break; } if (LocaleCompare((const char *) tag, "charcoal") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: charcoal can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { radius=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* charcoal image. */ { Image *newImage; newImage=CharcoalImage(msl_info->image[n],radius,sigma, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"chop") == 0) { Image *chop_image; /* Chop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } chop_image=ChopImage(msl_info->image[n],&geometry, &msl_info->image[n]->exception); if (chop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=chop_image; break; } if (LocaleCompare((const char *) tag,"color-floodfill") == 0) { PaintMethod paint_method; MagickPixelPacket target; /* Color floodfill image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryMagickColor(value,&target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorDatabase(value,&draw_info->fill, exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FloodfillPaintImage(msl_info->image[n],DefaultChannels, draw_info,&target,geometry.x,geometry.y, paint_method == FloodfillMethod ? MagickFalse : MagickTrue); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"comment") == 0) break; if (LocaleCompare((const char *) tag,"composite") == 0) { char composite_geometry[MaxTextExtent]; CompositeOperator compose; Image *composite_image, *rotate_image; PixelPacket target; /* Composite image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } composite_image=NewImageList(); compose=OverCompositeOp; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); compose=(CompositeOperator) option; break; } break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id"); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { composite_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: break; } } if (composite_image == (Image *) NULL) break; rotate_image=NewImageList(); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) SetImageArtifact(composite_image, "compose:args",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } if (LocaleCompare(keyword, "color") == 0) { (void) QueryColorDatabase(value, &composite_image->background_color,exception); break; } if (LocaleCompare(keyword,"compose") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixel(msl_info->image[n],geometry.x, geometry.y,&target,exception); break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); msl_info->image[n]->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"mask") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id"); if ((attribute != (const char *) NULL) && (LocaleCompare(value,value) == 0)) { SetImageType(composite_image,TrueColorMatteType); (void) CompositeImage(composite_image, CopyOpacityCompositeOp,msl_info->image[j],0,0); break; } } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { ssize_t opacity, y; register ssize_t x; register PixelPacket *q; CacheView *composite_view; opacity=QuantumRange-StringToLong(value); if (compose != DissolveCompositeOp) { (void) SetImageOpacity(composite_image,(Quantum) opacity); break; } (void) SetImageArtifact(msl_info->image[n], "compose:args",value); if (composite_image->matte != MagickTrue) (void) SetImageOpacity(composite_image,OpaqueOpacity); composite_view=AcquireAuthenticCacheView(composite_image, exception); for (y=0; y < (ssize_t) composite_image->rows ; y++) { q=GetCacheViewAuthenticPixels(composite_view,0,y, (ssize_t) composite_image->columns,1,exception); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (q->opacity == OpaqueOpacity) q->opacity=ClampToQuantum(opacity); q++; } if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse) break; } composite_view=DestroyCacheView(composite_view); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { rotate_image=RotateImage(composite_image, StringToDouble(value,(char **) NULL),exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"tile") == 0) { MagickBooleanType tile; option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); tile=(MagickBooleanType) option; (void) tile; if (rotate_image != (Image *) NULL) (void) SetImageArtifact(rotate_image, "compose:outside-overlay","false"); else (void) SetImageArtifact(composite_image, "compose:outside-overlay","false"); image=msl_info->image[n]; height=composite_image->rows; width=composite_image->columns; for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height) for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width) { if (rotate_image != (Image *) NULL) (void) CompositeImage(image,compose,rotate_image, x,y); else (void) CompositeImage(image,compose, composite_image,x,y); } if (rotate_image != (Image *) NULL) rotate_image=DestroyImage(rotate_image); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixel(msl_info->image[n],geometry.x, geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixel(msl_info->image[n],geometry.x, geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } image=msl_info->image[n]; (void) FormatLocaleString(composite_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns, (double) composite_image->rows,(double) geometry.x,(double) geometry.y); flags=ParseGravityGeometry(image,composite_geometry,&geometry, exception); if (rotate_image == (Image *) NULL) CompositeImageChannel(image,channel,compose,composite_image, geometry.x,geometry.y); else { /* Rotate image. */ geometry.x-=(ssize_t) (rotate_image->columns- composite_image->columns)/2; geometry.y-=(ssize_t) (rotate_image->rows-composite_image->rows)/2; CompositeImageChannel(image,channel,compose,rotate_image, geometry.x,geometry.y); rotate_image=DestroyImage(rotate_image); } composite_image=DestroyImage(composite_image); break; } if (LocaleCompare((const char *) tag,"contrast") == 0) { MagickBooleanType sharpen; /* Contrast image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } sharpen=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"sharpen") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); sharpen=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) ContrastImage(msl_info->image[n],sharpen); break; } if (LocaleCompare((const char *) tag,"crop") == 0) { Image *crop_image; /* Crop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } crop_image=CropImage(msl_info->image[n],&geometry, &msl_info->image[n]->exception); if (crop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=crop_image; break; } if (LocaleCompare((const char *) tag,"cycle-colormap") == 0) { ssize_t display; /* Cycle-colormap image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } display=0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"display") == 0) { display=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) CycleColormapImage(msl_info->image[n],display); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'D': case 'd': { if (LocaleCompare((const char *) tag,"despeckle") == 0) { Image *despeckle_image; /* Despeckle image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } despeckle_image=DespeckleImage(msl_info->image[n], &msl_info->image[n]->exception); if (despeckle_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=despeckle_image; break; } if (LocaleCompare((const char *) tag,"display") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) DisplayImages(msl_info->image_info[n],msl_info->image[n]); break; } if (LocaleCompare((const char *) tag,"draw") == 0) { char text[MaxTextExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value,&draw_info->fill, exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"points") == 0) { if (LocaleCompare(draw_info->primitive,"path") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); } else { (void) ConcatenateString(&draw_info->primitive," "); ConcatenateString(&draw_info->primitive,value); } break; } if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"primitive") == 0) { CloneString(&draw_info->primitive,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorDatabase(value,&draw_info->stroke, exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); (void) ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorDatabase(value,&draw_info->undercolor, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) DrawImage(msl_info->image[n],draw_info); draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'E': case 'e': { if (LocaleCompare((const char *) tag,"edge") == 0) { Image *edge_image; /* Edge image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } edge_image=EdgeImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (edge_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=edge_image; break; } if (LocaleCompare((const char *) tag,"emboss") == 0) { Image *emboss_image; /* Emboss image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,&msl_info->image[n]->exception); if (emboss_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=emboss_image; break; } if (LocaleCompare((const char *) tag,"enhance") == 0) { Image *enhance_image; /* Enhance image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } enhance_image=EnhanceImage(msl_info->image[n], &msl_info->image[n]->exception); if (enhance_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=enhance_image; break; } if (LocaleCompare((const char *) tag,"equalize") == 0) { /* Equalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) EqualizeImage(msl_info->image[n]); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'F': case 'f': { if (LocaleCompare((const char *) tag, "flatten") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; newImage=MergeImageLayers(msl_info->image[n],FlattenLayer, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"flip") == 0) { Image *flip_image; /* Flip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flip_image=FlipImage(msl_info->image[n], &msl_info->image[n]->exception); if (flip_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flip_image; break; } if (LocaleCompare((const char *) tag,"flop") == 0) { Image *flop_image; /* Flop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flop_image=FlopImage(msl_info->image[n], &msl_info->image[n]->exception); if (flop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flop_image; break; } if (LocaleCompare((const char *) tag,"frame") == 0) { FrameInfo frame_info; Image *frame_image; /* Frame image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) ResetMagickMemory(&frame_info,0,sizeof(frame_info)); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value, &msl_info->image[n]->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { frame_info.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"inner") == 0) { frame_info.inner_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"outer") == 0) { frame_info.outer_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { frame_info.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=msl_info->image[n]->columns+2*frame_info.x; frame_info.height=msl_info->image[n]->rows+2*frame_info.y; frame_image=FrameImage(msl_info->image[n],&frame_info, &msl_info->image[n]->exception); if (frame_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=frame_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'G': case 'g': { if (LocaleCompare((const char *) tag,"gamma") == 0) { char gamma[MaxTextExtent]; MagickPixelPacket pixel; /* Gamma image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } channel=UndefinedChannel; pixel.red=0.0; pixel.green=0.0; pixel.blue=0.0; *gamma='\0'; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blue") == 0) { pixel.blue=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { (void) CopyMagickString(gamma,value,MaxTextExtent); break; } if (LocaleCompare(keyword,"green") == 0) { pixel.green=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"red") == 0) { pixel.red=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } if (*gamma == '\0') (void) FormatLocaleString(gamma,MaxTextExtent,"%g,%g,%g", (double) pixel.red,(double) pixel.green,(double) pixel.blue); switch (channel) { default: { (void) GammaImage(msl_info->image[n],gamma); break; } case RedChannel: { (void) GammaImageChannel(msl_info->image[n],RedChannel,pixel.red); break; } case GreenChannel: { (void) GammaImageChannel(msl_info->image[n],GreenChannel, pixel.green); break; } case BlueChannel: { (void) GammaImageChannel(msl_info->image[n],BlueChannel, pixel.blue); break; } } break; } else if (LocaleCompare((const char *) tag,"get") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MaxTextExtent); switch (*keyword) { case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { (void) FormatLocaleString(value,MaxTextExtent,"%.20g", (double) msl_info->image[n]->rows); (void) SetImageProperty(msl_info->attributes[n],key,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { (void) FormatLocaleString(value,MaxTextExtent,"%.20g", (double) msl_info->image[n]->columns); (void) SetImageProperty(msl_info->attributes[n],key,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "group") == 0) { msl_info->number_groups++; msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory( msl_info->group_info,msl_info->number_groups+1UL, sizeof(*msl_info->group_info)); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'I': case 'i': { if (LocaleCompare((const char *) tag,"image") == 0) { MSLPushImage(msl_info,(Image *) NULL); if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { Image *next_image; (void) CopyMagickString(msl_info->image_info[n]->filename, "xc:",MaxTextExtent); (void) ConcatenateMagickString(msl_info->image_info[n]-> filename,value,MaxTextExtent); next_image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (next_image == (Image *) NULL) continue; if (msl_info->image[n] == (Image *) NULL) msl_info->image[n]=next_image; else { register Image *p; /* Link image into image list. */ p=msl_info->image[n]; while (p->next != (Image *) NULL) p=GetNextImageInList(p); next_image->previous=p; p->next=next_image; } break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"implode") == 0) { Image *implode_image; /* Implode image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"amount") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (implode_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=implode_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0) break; if (LocaleCompare((const char *) tag, "level") == 0) { double levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MaxTextExtent); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"black") == 0) { levelBlack = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { levelGamma = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"white") == 0) { levelWhite = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image */ { char level[MaxTextExtent + 1]; (void) FormatLocaleString(level,MaxTextExtent,"%3.6f/%3.6f/%3.6f/", levelBlack,levelGamma,levelWhite); LevelImage ( msl_info->image[n], level ); break; } } } case 'M': case 'm': { if (LocaleCompare((const char *) tag,"magnify") == 0) { Image *magnify_image; /* Magnify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } magnify_image=MagnifyImage(msl_info->image[n], &msl_info->image[n]->exception); if (magnify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=magnify_image; break; } if (LocaleCompare((const char *) tag,"map") == 0) { Image *affinity_image; MagickBooleanType dither; QuantizeInfo *quantize_info; /* Map image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } affinity_image=NewImageList(); dither=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); dither=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id"); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { affinity_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]); quantize_info->dither=dither; (void) RemapImages(quantize_info,msl_info->image[n], affinity_image); quantize_info=DestroyQuantizeInfo(quantize_info); affinity_image=DestroyImage(affinity_image); break; } if (LocaleCompare((const char *) tag,"matte-floodfill") == 0) { double opacity; MagickPixelPacket target; PaintMethod paint_method; /* Matte floodfill image. */ opacity=0.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryMagickColor(value,&target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { opacity=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualMagickPixel(msl_info->image[n], geometry.x,geometry.y,&target,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); draw_info->fill.opacity=ClampToQuantum(opacity); (void) FloodfillPaintImage(msl_info->image[n],OpacityChannel, draw_info,&target,geometry.x,geometry.y, paint_method == FloodfillMethod ? MagickFalse : MagickTrue); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"median-filter") == 0) { Image *median_image; /* Median-filter image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } median_image=StatisticImage(msl_info->image[n],MedianStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, &msl_info->image[n]->exception); if (median_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=median_image; break; } if (LocaleCompare((const char *) tag,"minify") == 0) { Image *minify_image; /* Minify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } minify_image=MinifyImage(msl_info->image[n], &msl_info->image[n]->exception); if (minify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=minify_image; break; } if (LocaleCompare((const char *) tag,"msl") == 0 ) break; if (LocaleCompare((const char *) tag,"modulate") == 0) { char modulate[MaxTextExtent]; /* Modulate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=100.0; geometry_info.sigma=100.0; geometry_info.xi=100.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blackness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"brightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"factor") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"hue") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'L': case 'l': { if (LocaleCompare(keyword,"lightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"saturation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"whiteness") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(modulate,MaxTextExtent,"%g,%g,%g", geometry_info.rho,geometry_info.sigma,geometry_info.xi); (void) ModulateImage(msl_info->image[n],modulate); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'N': case 'n': { if (LocaleCompare((const char *) tag,"negate") == 0) { MagickBooleanType gray; /* Negate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) NegateImageChannel(msl_info->image[n],channel,gray); break; } if (LocaleCompare((const char *) tag,"normalize") == 0) { /* Normalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) NormalizeImageChannel(msl_info->image[n],channel); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'O': case 'o': { if (LocaleCompare((const char *) tag,"oil-paint") == 0) { Image *paint_image; /* Oil-paint image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } if (LocaleCompare((const char *) tag,"opaque") == 0) { MagickPixelPacket fill_color, target; /* Opaque image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) QueryMagickColor("none",&target,exception); (void) QueryMagickColor("none",&fill_color,exception); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryMagickColor(value,&fill_color,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) OpaquePaintImageChannel(msl_info->image[n],channel, &target,&fill_color,MagickFalse); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'P': case 'p': { if (LocaleCompare((const char *) tag,"print") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'O': case 'o': { if (LocaleCompare(keyword,"output") == 0) { (void) FormatLocaleFile(stdout,"%s",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } if (LocaleCompare((const char *) tag, "profile") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); if (*keyword == '!') { /* Remove a profile from the image. */ (void) ProfileImage(msl_info->image[n],keyword, (const unsigned char *) NULL,0,MagickTrue); continue; } /* Associate a profile with the image. */ profile_info=CloneImageInfo(msl_info->image_info[n]); profile=GetImageProfile(msl_info->image[n],"iptc"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,keyword,exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { char name[MaxTextExtent], filename[MaxTextExtent]; register char *p; StringInfo *profile; (void) CopyMagickString(filename,keyword,MaxTextExtent); (void) CopyMagickString(name,keyword,MaxTextExtent); for (p=filename; *p != '\0'; p++) if ((*p == ':') && (IsPathDirectory(keyword) < 0) && (IsPathAccessible(keyword) == MagickFalse)) { register char *q; /* Look for profile name (e.g. name:profile). */ (void) CopyMagickString(name,filename,(size_t) (p-filename+1)); for (q=filename; *q != '\0'; q++) *q=(*++p); break; } profile=FileToStringInfo(filename,~0UL,exception); if (profile != (StringInfo *) NULL) { (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),MagickFalse); profile=DestroyStringInfo(profile); } continue; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),MagickFalse); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'Q': case 'q': { if (LocaleCompare((const char *) tag,"quantize") == 0) { QuantizeInfo quantize_info; /* Quantize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetQuantizeInfo(&quantize_info); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"colors") == 0) { quantize_info.number_colors=StringToLong(value); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); quantize_info.colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.dither=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"measure") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.measure_error=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"treedepth") == 0) { quantize_info.tree_depth=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) QuantizeImage(&quantize_info,msl_info->image[n]); break; } if (LocaleCompare((const char *) tag,"query-font-metrics") == 0) { char text[MaxTextExtent]; MagickBooleanType status; TypeMetric metrics; /* Query font metrics. */ draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value,&draw_info->fill, exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorDatabase(value,&draw_info->stroke, exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorDatabase(value,&draw_info->undercolor, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics); if (status != MagickFalse) { Image *image; image=msl_info->attributes[n]; FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x", "%g",metrics.pixels_per_em.x); FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y", "%g",metrics.pixels_per_em.y); FormatImageProperty(image,"msl:font-metrics.ascent","%g", metrics.ascent); FormatImageProperty(image,"msl:font-metrics.descent","%g", metrics.descent); FormatImageProperty(image,"msl:font-metrics.width","%g", metrics.width); FormatImageProperty(image,"msl:font-metrics.height","%g", metrics.height); FormatImageProperty(image,"msl:font-metrics.max_advance","%g", metrics.max_advance); FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g", metrics.bounds.x1); FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g", metrics.bounds.y1); FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g", metrics.bounds.x2); FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g", metrics.bounds.y2); FormatImageProperty(image,"msl:font-metrics.origin.x","%g", metrics.origin.x); FormatImageProperty(image,"msl:font-metrics.origin.y","%g", metrics.origin.y); } draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'R': case 'r': { if (LocaleCompare((const char *) tag,"raise") == 0) { MagickBooleanType raise; /* Raise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } raise=MagickFalse; SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"raise") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); raise=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) RaiseImage(msl_info->image[n],&geometry,raise); break; } if (LocaleCompare((const char *) tag,"read") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { Image *image; (void) CopyMagickString(msl_info->image_info[n]->filename, value,MaxTextExtent); image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (image == (Image *) NULL) continue; AppendImageToList(&msl_info->image[n],image); break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"reduce-noise") == 0) { Image *paint_image; /* Reduce-noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, &msl_info->image[n]->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } else if (LocaleCompare((const char *) tag,"repage") == 0) { /* init the values */ width=msl_info->image[n]->page.width; height=msl_info->image[n]->page.height; x=msl_info->image[n]->page.x; y=msl_info->image[n]->page.y; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { int flags; RectangleInfo geometry; flags=ParseAbsoluteGeometry(value,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; width=geometry.width; height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) x+=geometry.x; if ((flags & YValue) != 0) y+=geometry.y; } else { if ((flags & XValue) != 0) { x=geometry.x; if ((width == 0) && (geometry.x > 0)) width=msl_info->image[n]->columns+geometry.x; } if ((flags & YValue) != 0) { y=geometry.y; if ((height == 0) && (geometry.y > 0)) height=msl_info->image[n]->rows+geometry.y; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } msl_info->image[n]->page.width=width; msl_info->image[n]->page.height=height; msl_info->image[n]->page.x=x; msl_info->image[n]->page.y=y; break; } else if (LocaleCompare((const char *) tag,"resample") == 0) { double x_resolution, y_resolution; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; x_resolution=DefaultResolution; y_resolution=DefaultResolution; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'b': { if (LocaleCompare(keyword,"blur") == 0) { msl_info->image[n]->blur=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { ssize_t flags; flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma*=geometry_info.rho; x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x-resolution") == 0) { x_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y-resolution") == 0) { y_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* Resample image. */ { double factor; Image *resample_image; factor=1.0; if (msl_info->image[n]->units == PixelsPerCentimeterResolution) factor=2.54; width=(size_t) (x_resolution*msl_info->image[n]->columns/ (factor*(msl_info->image[n]->x_resolution == 0.0 ? DefaultResolution : msl_info->image[n]->x_resolution))+0.5); height=(size_t) (y_resolution*msl_info->image[n]->rows/ (factor*(msl_info->image[n]->y_resolution == 0.0 ? DefaultResolution : msl_info->image[n]->y_resolution))+0.5); resample_image=ResizeImage(msl_info->image[n],width,height, msl_info->image[n]->filter,msl_info->image[n]->blur, &msl_info->image[n]->exception); if (resample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resample_image; } break; } if (LocaleCompare((const char *) tag,"resize") == 0) { double blur; FilterTypes filter; Image *resize_image; /* Resize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } filter=UndefinedFilter; blur=1.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filter") == 0) { option=ParseCommandOption(MagickFilterOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); filter=(FilterTypes) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"support") == 0) { blur=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } resize_image=ResizeImage(msl_info->image[n],geometry.width, geometry.height,filter,blur,&msl_info->image[n]->exception); if (resize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resize_image; break; } if (LocaleCompare((const char *) tag,"roll") == 0) { Image *roll_image; /* Roll image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y, &msl_info->image[n]->exception); if (roll_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=roll_image; break; } else if (LocaleCompare((const char *) tag,"roll") == 0) { /* init the values */ width=msl_info->image[n]->columns; height=msl_info->image[n]->rows; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RollImage(msl_info->image[n], x, y, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"rotate") == 0) { Image *rotate_image; /* Rotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } rotate_image=RotateImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (rotate_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=rotate_image; break; } else if (LocaleCompare((const char *) tag,"rotate") == 0) { /* init the values */ double degrees = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { degrees = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RotateImage(msl_info->image[n], degrees, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'S': case 's': { if (LocaleCompare((const char *) tag,"sample") == 0) { Image *sample_image; /* Sample image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } sample_image=SampleImage(msl_info->image[n],geometry.width, geometry.height,&msl_info->image[n]->exception); if (sample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=sample_image; break; } if (LocaleCompare((const char *) tag,"scale") == 0) { Image *scale_image; /* Scale image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } scale_image=ScaleImage(msl_info->image[n],geometry.width, geometry.height,&msl_info->image[n]->exception); if (scale_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=scale_image; break; } if (LocaleCompare((const char *) tag,"segment") == 0) { ColorspaceType colorspace; MagickBooleanType verbose; /* Segment image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=1.0; geometry_info.sigma=1.5; colorspace=sRGBColorspace; verbose=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"cluster-threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.5; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"smoothing-threshold") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SegmentImage(msl_info->image[n],colorspace,verbose, geometry_info.rho,geometry_info.sigma); break; } else if (LocaleCompare((const char *) tag, "set") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"clip-mask") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id"); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],msl_info->image[j]); break; } } break; } if (LocaleCompare(keyword,"clip-path") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id"); if (LocaleCompare(property,value) == 0) { SetImageClipMask(msl_info->image[n],msl_info->image[j]); break; } } break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,value); if (colorspace < 0) ThrowMSLException(OptionError,"UnrecognizedColorspace", value); (void) TransformImageColorspace(msl_info->image[n], (ColorspaceType) colorspace); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { flags=ParseGeometry(value,&geometry_info); msl_info->image[n]->x_resolution=geometry_info.rho; msl_info->image[n]->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) msl_info->image[n]->y_resolution= msl_info->image[n]->x_resolution; break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value); break; } case 'O': case 'o': { if (LocaleCompare(keyword, "opacity") == 0) { ssize_t opac = OpaqueOpacity, len = (ssize_t) strlen( value ); if (value[len-1] == '%') { char tmp[100]; (void) CopyMagickString(tmp,value,len); opac = StringToLong( tmp ); opac = (int)(QuantumRange * ((float)opac/100)); } else opac = StringToLong( value ); (void) SetImageOpacity( msl_info->image[n], (Quantum) opac ); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value); break; } case 'P': case 'p': { if (LocaleCompare(keyword, "page") == 0) { char page[MaxTextExtent]; const char *image_option; MagickStatusType flags; RectangleInfo geometry; (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); image_option=GetImageArtifact(msl_info->image[n],"page"); if (image_option != (const char *) NULL) flags=ParseAbsoluteGeometry(image_option,&geometry); flags=ParseAbsoluteGeometry(value,&geometry); (void) FormatLocaleString(page,MaxTextExtent,"%.20gx%.20g", (double) geometry.width,(double) geometry.height); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) FormatLocaleString(page,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width, (double) geometry.height,(double) geometry.x,(double) geometry.y); (void) SetImageOption(msl_info->image_info[n],keyword,page); msl_info->image_info[n]->page=GetPageGeometry(page); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"shade") == 0) { Image *shade_image; MagickBooleanType gray; /* Shade image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"azimuth") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"elevation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho, geometry_info.sigma,&msl_info->image[n]->exception); if (shade_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shade_image; break; } if (LocaleCompare((const char *) tag,"shadow") == 0) { Image *shadow_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { geometry_info.rho=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.psi=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t) ceil(geometry_info.psi-0.5),&msl_info->image[n]->exception); if (shadow_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shadow_image; break; } if (LocaleCompare((const char *) tag,"sharpen") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: sharpen can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword, "radius") == 0) { radius = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* sharpen image. */ { Image *newImage; newImage=SharpenImage(msl_info->image[n],radius,sigma,&msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } else if (LocaleCompare((const char *) tag,"shave") == 0) { /* init the values */ width = height = 0; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; RectangleInfo rectInfo; rectInfo.height = height; rectInfo.width = width; rectInfo.x = x; rectInfo.y = y; newImage=ShaveImage(msl_info->image[n], &rectInfo, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"shear") == 0) { Image *shear_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorDatabase(value, &msl_info->image[n]->background_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shear_image=ShearImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,&msl_info->image[n]->exception); if (shear_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shear_image; break; } if (LocaleCompare((const char *) tag,"signature") == 0) { /* Signature image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SignatureImage(msl_info->image[n]); break; } if (LocaleCompare((const char *) tag,"solarize") == 0) { /* Solarize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=QuantumRange/2.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SolarizeImage(msl_info->image[n],geometry_info.rho); break; } if (LocaleCompare((const char *) tag,"spread") == 0) { Image *spread_image; /* Spread image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } spread_image=SpreadImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (spread_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=spread_image; break; } else if (LocaleCompare((const char *) tag,"stegano") == 0) { Image * watermark = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id"); if (theAttr && LocaleCompare(theAttr, value) == 0) { watermark = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( watermark != (Image*) NULL ) { Image *newImage; newImage=SteganoImage(msl_info->image[n], watermark, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"MissingWatermarkImage",keyword); } else if (LocaleCompare((const char *) tag,"stereo") == 0) { Image * stereoImage = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id"); if (theAttr && LocaleCompare(theAttr, value) == 0) { stereoImage = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( stereoImage != (Image*) NULL ) { Image *newImage; newImage=StereoImage(msl_info->image[n], stereoImage, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"Missing stereo image",keyword); } if (LocaleCompare((const char *) tag,"strip") == 0) { /* Strip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } (void) StripImage(msl_info->image[n]); break; } if (LocaleCompare((const char *) tag,"swap") == 0) { Image *p, *q, *swap; ssize_t index, swap_index; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } index=(-1); swap_index=(-2); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"indexes") == 0) { flags=ParseGeometry(value,&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) == 0) swap_index=(ssize_t) geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } /* Swap images. */ p=GetImageFromList(msl_info->image[n],index); q=GetImageFromList(msl_info->image[n],swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag); break; } swap=CloneImage(p,0,0,MagickTrue,&p->exception); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,&q->exception)); ReplaceImageInList(&q,swap); msl_info->image[n]=GetFirstImageInList(q); break; } if (LocaleCompare((const char *) tag,"swirl") == 0) { Image *swirl_image; /* Swirl image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho, &msl_info->image[n]->exception); if (swirl_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=swirl_image; break; } if (LocaleCompare((const char *) tag,"sync") == 0) { /* Sync image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SyncImage(msl_info->image[n]); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'T': case 't': { if (LocaleCompare((const char *) tag,"map") == 0) { Image *texture_image; /* Texture image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } texture_image=NewImageList(); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i]); CloneString(&value,attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id"); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { texture_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) TextureImage(msl_info->image[n],texture_image); texture_image=DestroyImage(texture_image); break; } else if (LocaleCompare((const char *) tag,"threshold") == 0) { /* init the values */ double threshold = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { threshold = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { BilevelImageChannel(msl_info->image[n], (ChannelType) ((ssize_t) (CompositeChannels &~ (ssize_t) OpacityChannel)), threshold); break; } } else if (LocaleCompare((const char *) tag, "transparent") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { MagickPixelPacket target; (void) QueryMagickColor(value,&target,exception); (void) TransparentPaintImage(msl_info->image[n],&target, TransparentOpacity,MagickFalse); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "trim") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; RectangleInfo rectInfo; /* all zeros on a crop == trim edges! */ rectInfo.height = rectInfo.width = 0; rectInfo.x = rectInfo.y = 0; newImage=CropImage(msl_info->image[n],&rectInfo, &msl_info->image[n]->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'W': case 'w': { if (LocaleCompare((const char *) tag,"write") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i])); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(msl_info->image[n]->filename,value, MaxTextExtent); break; } (void) SetMSLAttributes(msl_info,keyword,value); } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } /* process */ { *msl_info->image_info[n]->magick='\0'; (void) WriteImage(msl_info->image_info[n], msl_info->image[n]); break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } default: { ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } } if ( value != NULL ) value=DestroyString(value); exception=DestroyExceptionInfo(exception); (void) LogMagickEvent(CoderEvent,GetMagickModule()," )"); } Commit Message: Prevent fault in MSL interpreter CWE ID: CWE-20 Target: 1 Example 2: Code: decode_NXAST_RAW_CT_CLEAR(struct ofpbuf *out) { ofpact_put_CT_CLEAR(out); return 0; } 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: size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); return 1000000 - count; // give it 1 megabyte of stack #else return 1000000; // no stack depth check on this platform #endif } Commit Message: Fix stack size detection on Linux (fix #1427) 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: header_put_be_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_3byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 Target: 1 Example 2: Code: static int entersafe_select_aid(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len)==0 ) { if(file_out) { *file_out = sc_file_new(); if(!file_out) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card,in_path,file_out); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value,in_path->value,in_path->len); } if (file_out) { sc_file_t *file = *file_out; assert(file); file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name,in_path->value,in_path->len); file->namelen = in_path->len; file->id = 0x0000; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. 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 addReplyStatus(client *c, const char *status) { addReplyStatusLength(c,status,strlen(status)); } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. 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: image_transform_png_set_background_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_byte colour_type, bit_depth; png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */ int expand; png_color_16 back; /* We need a background colour, because we don't know exactly what transforms * have been set we have to supply the colour in the original file format and * so we need to know what that is! The background colour is stored in the * transform_display. */ RANDOMIZE(random_bytes); /* Read the random value, for colour type 3 the background colour is actually * expressed as a 24bit rgb, not an index. */ colour_type = that->this.colour_type; if (colour_type == 3) { colour_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; expand = 0; /* passing in an RGB not a pixel index */ } else { bit_depth = that->this.bit_depth; expand = 1; } image_pixel_init(&data, random_bytes, colour_type, bit_depth, 0/*x*/, 0/*unused: palette*/); /* Extract the background colour from this image_pixel, but make sure the * unused fields of 'back' are garbage. */ RANDOMIZE(back); if (colour_type & PNG_COLOR_MASK_COLOR) { back.red = (png_uint_16)data.red; back.green = (png_uint_16)data.green; back.blue = (png_uint_16)data.blue; } else back.gray = (png_uint_16)data.red; # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # else png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # endif this->next->set(this->next, that, pp, pi); } 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: static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } Commit Message: bpf: fix branch pruning logic when the verifier detects that register contains a runtime constant and it's compared with another constant it will prune exploration of the branch that is guaranteed not to be taken at runtime. This is all correct, but malicious program may be constructed in such a way that it always has a constant comparison and the other branch is never taken under any conditions. In this case such path through the program will not be explored by the verifier. It won't be taken at run-time either, but since all instructions are JITed the malicious program may cause JITs to complain about using reserved fields, etc. To fix the issue we have to track the instructions explored by the verifier and sanitize instructions that are dead at run time with NOPs. We cannot reject such dead code, since llvm generates it for valid C code, since it doesn't do as much data flow analysis as the verifier does. Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)") Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Daniel Borkmann <[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: bool IsSystemModal(aura::Window* window) { return window->transient_parent() && window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; } Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs. BUG=130420 TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient Review URL: https://chromiumcodereview.appspot.com/10514012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98 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: SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad, SplashColorMode modeA, GBool alphaA, GBool topDown) { width = widthA; height = heightA; mode = modeA; switch (mode) { case splashModeMono1: rowSize = (width + 7) >> 3; break; case splashModeMono8: rowSize = width; break; case splashModeRGB8: case splashModeBGR8: rowSize = width * 3; break; case splashModeXBGR8: rowSize = width * 4; break; #if SPLASH_CMYK case splashModeCMYK8: rowSize = width * 4; break; #endif } rowSize += rowPad - 1; rowSize -= rowSize % rowPad; data = (SplashColorPtr)gmalloc(rowSize * height); if (!topDown) { data += (height - 1) * rowSize; rowSize = -rowSize; } if (alphaA) { alpha = (Guchar *)gmalloc(width * height); } else { alpha = NULL; } } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static void vhost_scsi_free_cmd_map_res(struct vhost_scsi_nexus *nexus, struct se_session *se_sess) { struct vhost_scsi_cmd *tv_cmd; unsigned int i; if (!se_sess->sess_cmd_map) return; for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) { tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i]; kfree(tv_cmd->tvc_sgl); kfree(tv_cmd->tvc_prot_sgl); kfree(tv_cmd->tvc_upages); } } Commit Message: vhost/scsi: potential memory corruption This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt" to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16. I looked at the context and it turns out that in vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so anything higher than 255 then it is invalid. I have made that the limit now. In vhost_scsi_send_evt() we mask away values higher than 255, but now that the limit has changed, we don't need the mask. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas Bellinger <[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: void ManifestChangeNotifier::DidChangeManifest() { if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} 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: static int empty_write_end(struct page *page, unsigned from, unsigned to, int mode) { struct inode *inode = page->mapping->host; struct gfs2_inode *ip = GFS2_I(inode); struct buffer_head *bh; unsigned offset, blksize = 1 << inode->i_blkbits; pgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT; zero_user(page, from, to-from); mark_page_accessed(page); if (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) { if (!gfs2_is_writeback(ip)) gfs2_page_add_databufs(ip, page, from, to); block_commit_write(page, from, to); return 0; } offset = 0; bh = page_buffers(page); while (offset < to) { if (offset >= from) { set_buffer_uptodate(bh); mark_buffer_dirty(bh); clear_buffer_new(bh); write_dirty_buffer(bh, WRITE); } offset += blksize; bh = bh->b_this_page; } offset = 0; bh = page_buffers(page); while (offset < to) { if (offset >= from) { wait_on_buffer(bh); if (!buffer_uptodate(bh)) return -EIO; } offset += blksize; bh = bh->b_this_page; } return 0; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: const char* NoMeta(const char* str) { if (strchr(str, '%') != NULL) return "**** CORRUPTED FORMAT STRING ***"; return str; } Commit Message: Upgrade Visual studio 2017 15.8 - Upgrade to 15.8 - Add check on CGATS memory allocation (thanks to Quang Nguyen for pointing out this) 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: sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) { struct tcf_proto *cl = rcu_dereference_bh(dev->egress_cl_list); struct tcf_result cl_res; if (!cl) return skb; /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */ qdisc_bstats_cpu_update(cl->q, skb); switch (tcf_classify(skb, cl, &cl_res, false)) { case TC_ACT_OK: case TC_ACT_RECLASSIFY: skb->tc_index = TC_H_MIN(cl_res.classid); break; case TC_ACT_SHOT: qdisc_qstats_cpu_drop(cl->q); *ret = NET_XMIT_DROP; kfree_skb(skb); return NULL; case TC_ACT_STOLEN: case TC_ACT_QUEUED: case TC_ACT_TRAP: *ret = NET_XMIT_SUCCESS; consume_skb(skb); return NULL; case TC_ACT_REDIRECT: /* No need to push/pop skb's mac_header here on egress! */ skb_do_redirect(skb); *ret = NET_XMIT_SUCCESS; return NULL; default: break; } return skb; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); } 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 Target: 1 Example 2: Code: scoped_refptr<ShaderTranslatorInterface> GLES2DecoderImpl::GetTranslator( GLenum type) { return type == GL_VERTEX_SHADER ? vertex_translator_ : fragment_translator_; } 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: void Verify_FailStoreGroup() { EXPECT_FALSE(delegate()->stored_group_success_); EXPECT_TRUE(delegate()->would_exceed_quota_); AppCacheDatabase::GroupRecord group_record; AppCacheDatabase::CacheRecord cache_record; EXPECT_FALSE(database()->FindGroup(group_->group_id(), &group_record)); EXPECT_FALSE(database()->FindCache(cache_->cache_id(), &cache_record)); EXPECT_EQ(0, mock_quota_manager_proxy_->notify_storage_accessed_count_); EXPECT_EQ(0, mock_quota_manager_proxy_->notify_storage_modified_count_); TestFinished(); } 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:
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_state_from_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { int ret; u8 cpl; if (ctxt->ops->set_cr(ctxt, 3, tss->cr3)) return emulate_gp(ctxt, 0); ctxt->_eip = tss->eip; ctxt->eflags = tss->eflags | 2; /* General purpose registers */ *reg_write(ctxt, VCPU_REGS_RAX) = tss->eax; *reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx; *reg_write(ctxt, VCPU_REGS_RDX) = tss->edx; *reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx; *reg_write(ctxt, VCPU_REGS_RSP) = tss->esp; *reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp; *reg_write(ctxt, VCPU_REGS_RSI) = tss->esi; *reg_write(ctxt, VCPU_REGS_RDI) = tss->edi; /* * SDM says that segment selectors are loaded before segment * descriptors. This is important because CPL checks will * use CS.RPL. */ set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS); set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS); /* * If we're switching between Protected Mode and VM86, we need to make * sure to update the mode before loading the segment descriptors so * that the selectors are interpreted correctly. */ if (ctxt->eflags & X86_EFLAGS_VM) { ctxt->mode = X86EMUL_MODE_VM86; cpl = 3; } else { ctxt->mode = X86EMUL_MODE_PROT32; cpl = tss->cs & 3; } /* * Now load segment descriptors. If fault happenes at this stage * it is handled in a context of new task */ ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Handle errors when RIP is set during far jumps Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not handle this case, and may result in failed vm-entry once the assignment is done. The tricky part of doing so is that loading the new CS affects the VMCS/VMCB state, so if we fail during loading the new RIP, we are left in unconsistent state. Therefore, this patch saves on 64-bit the old CS descriptor and restores it if loading RIP failed. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_fs_info *fs_info = root->fs_info; struct list_head *next; struct extent_buffer *eb; int ret; ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) return ret; eb = btrfs_lock_root_node(fs_info->tree_root); ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL, 0, &eb); btrfs_tree_unlock(eb); free_extent_buffer(eb); if (ret) return ret; ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) return ret; ret = btrfs_run_dev_stats(trans, root->fs_info); WARN_ON(ret); ret = btrfs_run_dev_replace(trans, root->fs_info); WARN_ON(ret); ret = btrfs_run_qgroups(trans, root->fs_info); BUG_ON(ret); /* run_qgroups might have added some more refs */ ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); BUG_ON(ret); while (!list_empty(&fs_info->dirty_cowonly_roots)) { next = fs_info->dirty_cowonly_roots.next; list_del_init(next); root = list_entry(next, struct btrfs_root, dirty_list); ret = update_cowonly_root(trans, root); if (ret) return ret; } down_write(&fs_info->extent_commit_sem); switch_commit_root(fs_info->extent_root); up_write(&fs_info->extent_commit_sem); btrfs_after_dev_replace_commit(fs_info); return 0; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 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 char *escape_pathname(const char *inp) { const unsigned char *s; char *escaped, *d; if (!inp) { return NULL; } escaped = malloc (4 * strlen(inp) + 1); if (!escaped) { perror("malloc"); return NULL; } for (d = escaped, s = (const unsigned char *)inp; *s; s++) { if (needs_escape (*s)) { snprintf (d, 5, "\\x%02x", *s); d += strlen (d); } else { *d++ = *s; } } *d++ = '\0'; return escaped; } Commit Message: misc oom and possible memory leak fix 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: PaymentRequest::PaymentRequest( content::RenderFrameHost* render_frame_host, content::WebContents* web_contents, std::unique_ptr<ContentPaymentRequestDelegate> delegate, PaymentRequestWebContentsManager* manager, PaymentRequestDisplayManager* display_manager, mojo::InterfaceRequest<mojom::PaymentRequest> request, ObserverForTest* observer_for_testing) : web_contents_(web_contents), delegate_(std::move(delegate)), manager_(manager), display_manager_(display_manager), display_handle_(nullptr), binding_(this, std::move(request)), top_level_origin_(url_formatter::FormatUrlForSecurityDisplay( web_contents_->GetLastCommittedURL())), frame_origin_(url_formatter::FormatUrlForSecurityDisplay( render_frame_host->GetLastCommittedURL())), observer_for_testing_(observer_for_testing), journey_logger_(delegate_->IsIncognito(), ukm::GetSourceIdForWebContentsDocument(web_contents)), weak_ptr_factory_(this) { binding_.set_connection_error_handler(base::BindOnce( &PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr())); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189 Target: 1 Example 2: Code: static void callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } 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: xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; switch(ctxt->instate) { case XML_PARSER_CDATA_SECTION: return; case XML_PARSER_COMMENT: return; case XML_PARSER_START_TAG: return; case XML_PARSER_END_TAG: return; case XML_PARSER_EOF: xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL); return; case XML_PARSER_PROLOG: case XML_PARSER_START: case XML_PARSER_MISC: xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL); return; case XML_PARSER_ENTITY_DECL: case XML_PARSER_CONTENT: case XML_PARSER_ATTRIBUTE_VALUE: case XML_PARSER_PI: case XML_PARSER_SYSTEM_LITERAL: case XML_PARSER_PUBLIC_LITERAL: /* we just ignore it there */ return; case XML_PARSER_EPILOG: xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL); return; case XML_PARSER_ENTITY_VALUE: /* * NOTE: in the case of entity values, we don't do the * substitution here since we need the literal * entity value to be able to save the internal * subset of the document. * This will be handled by xmlStringDecodeEntities */ return; case XML_PARSER_DTD: /* * [WFC: Well-Formedness Constraint: PEs in Internal Subset] * In the internal DTD subset, parameter-entity references * can occur only where markup declarations can occur, not * within markup declarations. * In that case this is handled in xmlParseMarkupDecl */ if ((ctxt->external == 0) && (ctxt->inputNr == 1)) return; if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0) return; break; case XML_PARSER_IGNORE: return; } NEXT; name = xmlParseName(ctxt); if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "PEReference: %s\n", name); if (name == NULL) { xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL); } else { if (RAW == ';') { NEXT; if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); } else xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) || (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) { xmlChar start[4]; xmlCharEncoding enc; /* * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE * this is done independently. */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. * Note that, since we may have some non-UTF8 * encoding (like UTF16, bug 135229), the 'length' * is not known, but we can calculate based upon * the amount of data in the buffer. */ GROW if ((ctxt->input->end - ctxt->input->cur)>=4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); } } else { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "PEReference: %s is not a parameter entity\n", name); } } } else { xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); } } } 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: my_object_dict_of_dicts (MyObject *obj, GHashTable *in, GHashTable **out, GError **error) { *out = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, (GDestroyNotify) g_hash_table_destroy); g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out); return TRUE; } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: does_person_exist(const person_t* person) { int i; for (i = 0; i < s_num_persons; ++i) if (person == s_persons[i]) return true; return false; } Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268) * Fix integer overflow in layer_resize in map_engine.c There's a buffer overflow bug in the function layer_resize. It allocates a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`. But it didn't check for integer overflow, so if x_size and y_size are very large, it's possible that the buffer size is smaller than needed, causing a buffer overflow later. PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);` * move malloc to a separate line 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: static int usb_enumerate_device_otg(struct usb_device *udev) { int err = 0; #ifdef CONFIG_USB_OTG /* * OTG-aware devices on OTG-capable root hubs may be able to use SRP, * to wake us after we've powered off VBUS; and HNP, switching roles * "host" to "peripheral". The OTG descriptor helps figure this out. */ if (!udev->bus->is_b_host && udev->config && udev->parent == udev->bus->root_hub) { struct usb_otg_descriptor *desc = NULL; struct usb_bus *bus = udev->bus; unsigned port1 = udev->portnum; /* descriptor may appear anywhere in config */ err = __usb_get_extra_descriptor(udev->rawdescriptors[0], le16_to_cpu(udev->config[0].desc.wTotalLength), USB_DT_OTG, (void **) &desc); if (err || !(desc->bmAttributes & USB_OTG_HNP)) return 0; dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n", (port1 == bus->otg_port) ? "" : "non-"); /* enable HNP before suspend, it's simpler */ if (port1 == bus->otg_port) { bus->b_hnp_enable = 1; err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_B_HNP_ENABLE, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) { /* * OTG MESSAGE: report errors here, * customize to match your product. */ dev_err(&udev->dev, "can't set HNP mode: %d\n", err); bus->b_hnp_enable = 0; } } else if (desc->bLength == sizeof (struct usb_otg_descriptor)) { /* Set a_alt_hnp_support for legacy otg device */ err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_A_ALT_HNP_SUPPORT, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) dev_err(&udev->dev, "set a_alt_hnp_support failed: %d\n", err); } } #endif return err; } 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:
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 construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; } Commit Message: KEYS: add missing permission check for request_key() destination When the request_key() syscall is not passed a destination keyring, it links the requested key (if constructed) into the "default" request-key keyring. This should require Write permission to the keyring. However, there is actually no permission check. This can be abused to add keys to any keyring to which only Search permission is granted. This is because Search permission allows joining the keyring. keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_SESSION_KEYRING) then will set the default request-key keyring to the session keyring. Then, request_key() can be used to add keys to the keyring. Both negatively and positively instantiated keys can be added using this method. Adding negative keys is trivial. Adding a positive key is a bit trickier. It requires that either /sbin/request-key positively instantiates the key, or that another thread adds the key to the process keyring at just the right time, such that request_key() misses it initially but then finds it in construct_alloc_key(). Fix this bug by checking for Write permission to the keyring in construct_get_dest_keyring() when the default keyring is being used. We don't do the permission check for non-default keyrings because that was already done by the earlier call to lookup_user_key(). Also, request_key_and_link() is currently passed a 'struct key *' rather than a key_ref_t, so the "possessed" bit is unavailable. We also don't do the permission check for the "requestor keyring", to continue to support the use case described by commit 8bbf4976b59f ("KEYS: Alter use of key instantiation link-to-keyring argument") where /sbin/request-key recursively calls request_key() to add keys to the original requestor's destination keyring. (I don't know of any users who actually do that, though...) Fixes: 3e30148c3d52 ("[PATCH] Keys: Make request-key create an authorisation key") Cc: <[email protected]> # v2.6.13+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-862 Target: 1 Example 2: Code: static int ssl3_check_client_certificate(SSL *s) { if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey) return 0; /* If no suitable signature algorithm can't use certificate */ if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys]) return 0; /* * If strict mode check suitability of chain before using it. This also * adjusts suite B digest if necessary. */ if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT && !tls1_check_chain(s, NULL, NULL, NULL, -2)) return 0; return 1; } Commit Message: Fix missing NULL checks in CKE processing Reviewed-by: Rich Salz <[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: void CheckCanDownload( const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, const GURL& url, const std::string& request_method, CanDownloadCallback can_download_cb) { DownloadRequestLimiter* limiter = g_browser_process->download_request_limiter(); if (limiter) { DownloadRequestLimiter::Callback cb = base::Bind(&CheckDownloadComplete, base::Passed(&can_download_cb)); limiter->CanDownload(web_contents_getter, url, request_method, cb); } } Commit Message: Downloads : Fixed an issue of opening incorrect download file When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download. Bug: 793620 Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8 Reviewed-on: https://chromium-review.googlesource.com/826477 Reviewed-by: David Trainor <[email protected]> Reviewed-by: Xing Liu <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Commit-Queue: Shakti Sahu <[email protected]> Cr-Commit-Position: refs/heads/master@{#525810} 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: int svc_rdma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, struct svc_rdma_req_map *vec, bool write_chunk_present) { int sge_no; u32 sge_bytes; u32 page_bytes; u32 page_off; int page_no; if (xdr->len != (xdr->head[0].iov_len + xdr->page_len + xdr->tail[0].iov_len)) { pr_err("svcrdma: %s: XDR buffer length error\n", __func__); return -EIO; } /* Skip the first sge, this is for the RPCRDMA header */ sge_no = 1; /* Head SGE */ vec->sge[sge_no].iov_base = xdr->head[0].iov_base; vec->sge[sge_no].iov_len = xdr->head[0].iov_len; sge_no++; /* pages SGE */ page_no = 0; page_bytes = xdr->page_len; page_off = xdr->page_base; while (page_bytes) { vec->sge[sge_no].iov_base = page_address(xdr->pages[page_no]) + page_off; sge_bytes = min_t(u32, page_bytes, (PAGE_SIZE - page_off)); page_bytes -= sge_bytes; vec->sge[sge_no].iov_len = sge_bytes; sge_no++; page_no++; page_off = 0; /* reset for next time through loop */ } /* Tail SGE */ if (xdr->tail[0].iov_len) { unsigned char *base = xdr->tail[0].iov_base; size_t len = xdr->tail[0].iov_len; u32 xdr_pad = xdr_padsize(xdr->page_len); if (write_chunk_present && xdr_pad) { base += xdr_pad; len -= xdr_pad; } if (len) { vec->sge[sge_no].iov_base = base; vec->sge[sge_no].iov_len = len; sge_no++; } } dprintk("svcrdma: %s: sge_no %d page_no %d " "page_base %u page_len %u head_len %zu tail_len %zu\n", __func__, sge_no, page_no, xdr->page_base, xdr->page_len, xdr->head[0].iov_len, xdr->tail[0].iov_len); vec->count = sge_no; return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 1 Example 2: Code: static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff) { const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams; DEBUGLOG(4, "copying dictionary into context"); { unsigned const windowLog = params.cParams.windowLog; assert(windowLog != 0); /* Copy only compression parameters related to tables. */ params.cParams = *cdict_cParams; params.cParams.windowLog = windowLog; ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize, ZSTDcrp_noMemset, zbuff); assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy); assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog); assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog); } /* copy tables */ { size_t const chainSize = (cdict_cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cdict_cParams->chainLog); size_t const hSize = (size_t)1 << cdict_cParams->hashLog; size_t const tableSpace = (chainSize + hSize) * sizeof(U32); assert((U32*)cctx->blockState.matchState.chainTable == (U32*)cctx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */ assert((U32*)cctx->blockState.matchState.hashTable3 == (U32*)cctx->blockState.matchState.chainTable + chainSize); assert((U32*)cdict->matchState.chainTable == (U32*)cdict->matchState.hashTable + hSize); /* chainTable must follow hashTable */ assert((U32*)cdict->matchState.hashTable3 == (U32*)cdict->matchState.chainTable + chainSize); memcpy(cctx->blockState.matchState.hashTable, cdict->matchState.hashTable, tableSpace); /* presumes all tables follow each other */ } /* Zero the hashTable3, since the cdict never fills it */ { size_t const h3Size = (size_t)1 << cctx->blockState.matchState.hashLog3; assert(cdict->matchState.hashLog3 == 0); memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32)); } /* copy dictionary offsets */ { ZSTD_matchState_t const* srcMatchState = &cdict->matchState; ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState; dstMatchState->window = srcMatchState->window; dstMatchState->nextToUpdate = srcMatchState->nextToUpdate; dstMatchState->nextToUpdate3= srcMatchState->nextToUpdate3; dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd; } cctx->dictID = cdict->dictID; /* copy block state */ memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState)); return 0; } Commit Message: fixed T36302429 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: int perf_event_exit_cpu(unsigned int cpu) { perf_event_exit_cpu_context(cpu); return 0; } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Kees Cook <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Min Chong <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[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: bool BluetoothDeviceChromeOS::ExpectingConfirmation() const { return !confirmation_callback_.is_null(); } 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: static struct ctl_table *sd_alloc_ctl_entry(int n) { struct ctl_table *entry = kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); return entry; } 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: void GLManager::SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) { command_buffer_->SignalSyncToken( sync_token, base::AdaptCallbackForRepeating(std::move(callback))); } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 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: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <[email protected]> Commit-Queue: vikas soni <[email protected]> Cr-Commit-Position: refs/heads/master@{#539111} 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: rsvp_obj_print(netdissect_options *ndo, const u_char *pptr, u_int plen, const u_char *tptr, const char *ident, u_int tlen, const struct rsvp_common_header *rsvp_com_header) { const struct rsvp_object_header *rsvp_obj_header; const u_char *obj_tptr; union { const struct rsvp_obj_integrity_t *rsvp_obj_integrity; const struct rsvp_obj_frr_t *rsvp_obj_frr; } obj_ptr; u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; union { float f; uint32_t i; } bw; uint8_t namelen; u_int action, subchannel; while(tlen>=sizeof(struct rsvp_object_header)) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); rsvp_obj_header = (const struct rsvp_object_header *)tptr; rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); rsvp_obj_ctype=rsvp_obj_header->ctype; if(rsvp_obj_len % 4) { ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len)); return -1; } if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len, (unsigned long)sizeof(const struct rsvp_object_header))); return -1; } ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s", ident, tok2str(rsvp_obj_values, "Unknown", rsvp_obj_header->class_num), rsvp_obj_header->class_num, ((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject")); if (rsvp_obj_header->class_num > 128) ND_PRINT((ndo, " %s", ((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently")); ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u", tok2str(rsvp_ctype_values, "Unknown", ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), rsvp_obj_ctype, rsvp_obj_len)); if(tlen < rsvp_obj_len) { ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident)); return -1; } obj_tptr=tptr+sizeof(struct rsvp_object_header); obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); /* did we capture enough for fully decoding the object ? */ if (!ND_TTEST2(*tptr, rsvp_obj_len)) return -1; hexdump=FALSE; switch(rsvp_obj_header->class_num) { case RSVP_OBJ_SESSION: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return -1; ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+5), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return -1; ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in6_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+sizeof(struct in6_addr)+1), EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 36) return -1; ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ip6addr_string(ndo, obj_tptr + 20))); obj_tlen-=36; obj_tptr+=36; break; case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ if (obj_tlen < 26) return -1; ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+6), ip6addr_string(ndo, obj_tptr + 8))); obj_tlen-=26; obj_tptr+=26; break; case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_TUNNEL_IPV4: case RSVP_CTYPE_UNI_IPV4: if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_CONFIRM: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Receiver Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return -1; ND_PRINT((ndo, "%s IPv6 Receiver Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_NOTIFY_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return-1; ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ case RSVP_OBJ_LABEL: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Generalized Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u", ident, EXTRACT_32BITS(obj_tptr), ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_STYLE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]", ident, tok2str(rsvp_resstyle_values, "Unknown", EXTRACT_24BITS(obj_tptr+1)), *(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SENDER_TEMPLATE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" )); ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+4))&0xfff, (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+8))&0xfff, (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI", ident, (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "", (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : "")); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)", ident, tok2str(gmpls_encoding_values, "Unknown", *obj_tptr), *obj_tptr)); ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)", ident, tok2str(gmpls_switch_cap_values, "Unknown", *(obj_tptr+1)), *(obj_tptr+1), tok2str(gmpls_payload_values, "Unknown", EXTRACT_16BITS(obj_tptr+2)), EXTRACT_16BITS(obj_tptr + 2))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RRO: case RSVP_OBJ_ERO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: while(obj_tlen >= 4 ) { u_char length; ND_TCHECK2(*obj_tptr, 4); length = *(obj_tptr + 1); ND_PRINT((ndo, "%s Subobject Type: %s, length %u", ident, tok2str(rsvp_obj_xro_values, "Unknown %u", RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), length)); if (length == 0) { /* prevent infinite loops */ ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident)); break; } switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { u_char prefix_length; case RSVP_OBJ_XRO_IPV4: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); prefix_length = *(obj_tptr+6); if (prefix_length != 32) { ND_PRINT((ndo, " ERROR: Prefix length %u != 32", prefix_length)); goto invalid; } ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]", RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict", ipaddr_string(ndo, obj_tptr+2), *(obj_tptr+6), bittok2str(rsvp_obj_rro_flag_values, "none", *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ break; case RSVP_OBJ_XRO_LABEL: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u", bittok2str(rsvp_obj_rro_label_flag_values, "none", *(obj_tptr+2)), *(obj_tptr+2), tok2str(rsvp_ctype_values, "Unknown", *(obj_tptr+3) + 256*RSVP_OBJ_RRO), *(obj_tptr+3), EXTRACT_32BITS(obj_tptr + 4))); } obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_HELLO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RESTART_CAPABILITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SESSION_ATTRIBUTE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 4) return-1; namelen = *(obj_tptr+3); if (obj_tlen < 4+namelen) return-1; ND_PRINT((ndo, "%s Session Name: ", ident)); for (i = 0; i < namelen; i++) safeputchar(ndo, *(obj_tptr + 4 + i)); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)", ident, (int)*obj_tptr, (int)*(obj_tptr+1), bittok2str(rsvp_session_attribute_flag_values, "none", *(obj_tptr+2)), *(obj_tptr + 2))); obj_tlen-=4+*(obj_tptr+3); obj_tptr+=4+*(obj_tptr+3); break; default: hexdump=TRUE; } break; case RSVP_OBJ_GENERALIZED_UNI: switch(rsvp_obj_ctype) { int subobj_type,af,subobj_len,total_subobj_len; case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; /* read variable length subobjects */ total_subobj_len = obj_tlen; while(total_subobj_len > 0) { subobj_len = EXTRACT_16BITS(obj_tptr); subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u", ident, tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type), subobj_type, tok2str(af_values, "Unknown", af), af, subobj_len)); if(subobj_len == 0) goto invalid; switch(subobj_type) { case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: switch(af) { case AFNUM_INET: if (subobj_len < 8) return -1; ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s", ident, ipaddr_string(ndo, obj_tptr + 4))); break; case AFNUM_INET6: if (subobj_len < 20) return -1; ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s", ident, ip6addr_string(ndo, obj_tptr + 4))); break; case AFNUM_NSAP: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; } break; case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: if (subobj_len < 16) { return -1; } ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u", ident, ((EXTRACT_32BITS(obj_tptr+4))>>31), ((EXTRACT_32BITS(obj_tptr+4))&0xFF), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr + 12))); break; case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: if (subobj_len < 8) { return -1; } ND_PRINT((ndo, "%s Service level: %u", ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); break; default: hexdump=TRUE; break; } total_subobj_len-=subobj_len; obj_tptr+=subobj_len; obj_tlen+=subobj_len; } if (total_subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_RSVP_HOP: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; if (obj_tlen) hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 16))); obj_tlen-=20; obj_tptr+=20; hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; default: hexdump=TRUE; } break; case RSVP_OBJ_TIME_VALUES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Refresh Period: %ums", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; /* those three objects do share the same semantics */ case RSVP_OBJ_SENDER_TSPEC: case RSVP_OBJ_ADSPEC: case RSVP_OBJ_FLOWSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Msg-Version: %u, length: %u", ident, (*obj_tptr & 0xf0) >> 4, EXTRACT_16BITS(obj_tptr + 2) << 2)); obj_tptr+=4; /* get to the start of the service header */ obj_tlen-=4; while (obj_tlen >= 4) { intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u", ident, tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)), *(obj_tptr), (*(obj_tptr+1)&0x80) ? "" : "not", intserv_serv_tlen)); obj_tptr+=4; /* get to the start of the parameter list */ obj_tlen-=4; while (intserv_serv_tlen>=4) { processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); if (processed == 0) break; obj_tlen-=processed; intserv_serv_tlen-=processed; obj_tptr+=processed; } } break; default: hexdump=TRUE; } break; case RSVP_OBJ_FILTERSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_3: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_24BITS(obj_tptr + 17))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_FASTREROUTE: /* the differences between c-type 1 and 7 are minor */ obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: /* new style */ if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); obj_tlen-=sizeof(struct rsvp_obj_frr_t); obj_tptr+=sizeof(struct rsvp_obj_frr_t); break; case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ if (obj_tlen < 16) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_DETOUR: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: while(obj_tlen >= 8) { ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s", ident, ipaddr_string(ndo, obj_tptr), ipaddr_string(ndo, obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_CLASSTYPE: case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: ND_PRINT((ndo, "%s CT: %u", ident, EXTRACT_32BITS(obj_tptr) & 0x7)); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_ERROR_SPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; error_code=*(obj_tptr+5); error_value=EXTRACT_16BITS(obj_tptr+6); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr+4), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value), error_value)); break; default: ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value)); break; } obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; error_code=*(obj_tptr+17); error_value=EXTRACT_16BITS(obj_tptr+18); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr+16), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; default: break; } obj_tlen-=20; obj_tptr+=20; break; default: hexdump=TRUE; } break; case RSVP_OBJ_PROPERTIES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; padbytes = EXTRACT_16BITS(obj_tptr+2); ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u", ident, EXTRACT_16BITS(obj_tptr), padbytes)); obj_tlen-=4; obj_tptr+=4; /* loop through as long there is anything longer than the TLV header (2) */ while(obj_tlen >= 2 + padbytes) { ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */ ident, tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr), *obj_tptr, *(obj_tptr + 1))); if (obj_tlen < *(obj_tptr+1)) return-1; if (*(obj_tptr+1) < 2) return -1; print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2); obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_MESSAGE_ID: /* fall through */ case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ case RSVP_OBJ_MESSAGE_ID_LIST: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u", ident, *obj_tptr, EXTRACT_24BITS(obj_tptr + 1))); obj_tlen-=4; obj_tptr+=4; /* loop through as long there are no messages left */ while(obj_tlen >= 4) { ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_INTEGRITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) return-1; obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]", ident, EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), bittok2str(rsvp_obj_integrity_flag_values, "none", obj_ptr.rsvp_obj_integrity->flags))); ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); sigcheck = signature_verify(ndo, pptr, plen, obj_ptr.rsvp_obj_integrity->digest, rsvp_clear_checksum, rsvp_com_header); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); obj_tlen+=sizeof(struct rsvp_obj_integrity_t); obj_tptr+=sizeof(struct rsvp_obj_integrity_t); break; default: hexdump=TRUE; } break; case RSVP_OBJ_ADMIN_STATUS: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Flags [%s]", ident, bittok2str(rsvp_obj_admin_status_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_SET: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; action = (EXTRACT_16BITS(obj_tptr)>>8); ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident, tok2str(rsvp_obj_label_set_action_values, "Unknown", action), action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); switch (action) { case LABEL_SET_INCLUSIVE_RANGE: case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ /* only a couple of subchannels are expected */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: obj_tlen-=4; obj_tptr+=4; subchannel = 1; while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel, EXTRACT_32BITS(obj_tptr))); obj_tptr+=4; obj_tlen-=4; subchannel++; } break; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_S2L: switch (rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case RSVP_OBJ_SCOPE: case RSVP_OBJ_POLICY_DATA: case RSVP_OBJ_ACCEPT_LABEL_SET: case RSVP_OBJ_PROTECTION: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */ break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || hexdump == TRUE) print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */ rsvp_obj_len - sizeof(struct rsvp_object_header)); tptr+=rsvp_obj_len; tlen-=rsvp_obj_len; } return 0; invalid: ND_PRINT((ndo, "%s", istr)); return -1; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return -1; } Commit Message: CVE-2017-13051/RSVP: fix bounds checks for UNI Fixup the part of rsvp_obj_print() that decodes the GENERALIZED_UNI object from RFC 3476 Section 3.1 to check the sub-objects inside that object more thoroughly. 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: void ChildProcessSecurityPolicyImpl::GrantCopyIntoFileSystem( int child_id, const std::string& filesystem_id) { GrantPermissionsForFileSystem(child_id, filesystem_id, COPY_INTO_FILE_GRANT); } Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs. BUG=528505,226927 Review URL: https://codereview.chromium.org/1362433002 Cr-Commit-Position: refs/heads/master@{#351705} 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: void __init files_init(unsigned long mempages) { unsigned long n; filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); /* * One file with associated inode and dcache is very roughly 1K. * Per default don't use more than 10% of our memory for files. */ n = (mempages * (PAGE_SIZE / 1024)) / 10; files_stat.max_files = max_t(unsigned long, n, NR_FILE); files_defer_init(); lg_lock_init(&files_lglock, "files_lglock"); percpu_counter_init(&nr_files, 0); } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17 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 Image *ReadJBIGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; IndexPacket index; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t length, y; struct jbg_dec_state jbig_info; unsigned char bit, *buffer, byte; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JBIG toolkit. */ jbg_dec_init(&jbig_info); jbg_dec_maxsize(&jbig_info,(unsigned long) image->columns,(unsigned long) image->rows); image->columns=jbg_dec_getwidth(&jbig_info); image->rows=jbg_dec_getheight(&jbig_info); image->depth=8; image->storage_class=PseudoClass; image->colors=2; /* Read JBIG file. */ buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=JBG_EAGAIN; do { length=(ssize_t) ReadBlob(image,MagickMaxBufferExtent,buffer); if (length == 0) break; p=buffer; while ((length > 0) && ((status == JBG_EAGAIN) || (status == JBG_EOK))) { size_t count; status=jbg_dec_in(&jbig_info,p,length,&count); p+=count; length-=(ssize_t) count; } } while ((status == JBG_EAGAIN) || (status == JBG_EOK)); /* Create colormap. */ image->columns=jbg_dec_getwidth(&jbig_info); image->rows=jbg_dec_getheight(&jbig_info); image->compression=JBIG2Compression; if (AcquireImageColormap(image,2) == MagickFalse) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } image->colormap[0].red=0; image->colormap[0].green=0; image->colormap[0].blue=0; image->colormap[1].red=QuantumRange; image->colormap[1].green=QuantumRange; image->colormap[1].blue=QuantumRange; image->x_resolution=300; image->y_resolution=300; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert X bitmap image to pixel packets. */ p=jbg_dec_getimage(&jbig_info,0); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(*p++); index=(byte & 0x80) ? 0 : 1; bit++; byte<<=1; if (bit == 8) bit=0; SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free scale resource. */ jbg_dec_free(&jbig_info); buffer=(unsigned char *) RelinquishMagickMemory(buffer); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: int lookup_journal_in_cursum(struct f2fs_journal *journal, int type, unsigned int val, int alloc) { int i; if (type == NAT_JOURNAL) { for (i = 0; i < nats_in_cursum(journal); i++) { if (le32_to_cpu(nid_in_journal(journal, i)) == val) return i; } if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL)) return update_nats_in_cursum(journal, 1); } else if (type == SIT_JOURNAL) { for (i = 0; i < sits_in_cursum(journal); i++) if (le32_to_cpu(segno_in_journal(journal, i)) == val) return i; if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL)) return update_sits_in_cursum(journal, 1); } return -1; } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <[email protected]> Signed-off-by: Jaegeuk Kim <[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: void RenderViewImpl::didCreateDataSource(WebFrame* frame, WebDataSource* ds) { DocumentState* document_state = DocumentState::FromDataSource(ds); if (!document_state) { document_state = new DocumentState; ds->setExtraData(document_state); } bool content_initiated = !pending_navigation_params_.get(); if (content_initiated) document_state->set_navigation_state( NavigationState::CreateContentInitiated()); else PopulateStateFromPendingNavigationParams(document_state); if (webview()) { if (WebFrame* old_frame = webview()->mainFrame()) { const WebURLRequest& original_request = ds->originalRequest(); const GURL referrer( original_request.httpHeaderField(WebString::fromUTF8("Referer"))); if (!referrer.is_empty() && DocumentState::FromDataSource( old_frame->dataSource())->was_prefetcher()) { for (;old_frame;old_frame = old_frame->traverseNext(false)) { WebDataSource* old_frame_ds = old_frame->dataSource(); if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) { document_state->set_was_referred_by_prefetcher(true); break; } } } } } if (content_initiated) { const WebURLRequest& request = ds->request(); switch (request.cachePolicy()) { case WebURLRequest::UseProtocolCachePolicy: // normal load. document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL); break; case WebURLRequest::ReloadIgnoringCacheData: // reload. document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD); break; case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data. document_state->set_load_type( DocumentState::LINK_LOAD_CACHE_STALE_OK); break; case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post. document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY); break; } } FOR_EACH_OBSERVER( RenderViewObserver, observers_, DidCreateDataSource(frame, ds)); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 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: int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc) { xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLXconfig *config; __GLXscreen *pGlxScreen; int err; if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) return err; if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) config, pGlxScreen, req->isDirect); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void rsp_increment(struct x86_emulate_ctxt *ctxt, int inc) { masked_increment(reg_rmw(ctxt, VCPU_REGS_RSP), stack_mask(ctxt), inc); } Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <[email protected]> Cc: [email protected] Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <[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: bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context) { uint8_t tmp = 0; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context)); asn1_read_uint8(data, &tmp); if (tmp == 0xFF) { *v = true; } else { *v = false; } asn1_end_tag(data); return !data->has_error; } Commit Message: 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 AXLayoutObject::supportsARIADragging() const { const AtomicString& grabbed = getAttribute(aria_grabbedAttr); return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false"); } 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: 1 Example 2: Code: gs_main_init0(gs_main_instance * minst, FILE * in, FILE * out, FILE * err, int max_lib_paths) { ref *array; /* Do platform-dependent initialization. */ /* We have to do this as the very first thing, */ /* because it detects attempts to run 80N86 executables (N>0) */ /* on incompatible processors. */ gp_init(); /* Initialize the imager. */ /* Reset debugging flags */ #ifdef PACIFY_VALGRIND VALGRIND_HG_DISABLE_CHECKING(gs_debug, 128); #endif memset(gs_debug, 0, 128); gs_log_errors = 0; /* gs_debug['#'] = 0 */ gp_get_realtime(minst->base_time); /* Initialize the file search paths. */ array = (ref *) gs_alloc_byte_array(minst->heap, max_lib_paths, sizeof(ref), "lib_path array"); if (array == 0) { gs_lib_finit(1, gs_error_VMerror, minst->heap); return_error(gs_error_VMerror); } make_array(&minst->lib_path.container, avm_foreign, max_lib_paths, array); make_array(&minst->lib_path.list, avm_foreign | a_readonly, 0, minst->lib_path.container.value.refs); minst->lib_path.env = 0; minst->lib_path.final = 0; minst->lib_path.count = 0; minst->user_errors = 1; minst->init_done = 0; return 0; } 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: RETSIGTYPE requestinfo(int signo _U_) { if (infodelay) ++infoprint; else info(0); } Commit Message: (for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely get_next_file() did not check the return value of strlen() and underflowed an array index if the line read by fgets() from the file started with \0. This caused an out-of-bounds read and could cause a write. Add the missing check. This vulnerability was discovered by Brian Carpenter & Geeknik Labs. CWE ID: CWE-120 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: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket, int newUid, uid_t callerUid) { ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__); const int fd = socket.get(); struct stat info; if (fstat(fd, &info)) { return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor"); } if (info.st_uid != callerUid) { return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls"); } if (S_ISSOCK(info.st_mode) == 0) { return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket"); } int optval; socklen_t optlen; netdutils::Status status = getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen); if (status != netdutils::status::ok) { return status; } if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) { return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set"); } if (fchown(fd, newUid, -1)) { return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor"); } return netdutils::status::ok; } Commit Message: Set optlen for UDP-encap check in XfrmController When setting the socket owner for an encap socket XfrmController will first attempt to verify that the socket has the UDP-encap socket option set. When doing so it would pass in an uninitialized optlen parameter which could cause the call to not modify the option value if the optlen happened to be too short. So for example if the stack happened to contain a zero where optlen was located the check would fail and the socket owner would not be changed. Fix this by setting optlen to the size of the option value parameter. Test: run cts -m CtsNetTestCases BUG: 111650288 Change-Id: I57b6e9dba09c1acda71e3ec2084652e961667bd9 (cherry picked from commit fc42a105147310bd680952d4b71fe32974bd8506) CWE ID: CWE-909 Target: 1 Example 2: Code: static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen) { size_t i; for (i = 0; i < tlen; i++) { if (table[i].nid == nid) return table[i].id; } return -1; } Commit Message: 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 snd_seq_ioctl_remove_events(struct snd_seq_client *client, void __user *arg) { struct snd_seq_remove_events info; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; /* * Input mostly not implemented XXX. */ if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) { /* * No restrictions so for a user client we can clear * the whole fifo */ if (client->type == USER_CLIENT) snd_seq_fifo_clear(client->data.user.fifo); } if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT) snd_seq_queue_remove_cells(client->number, &info); return 0; } Commit Message: ALSA: seq: Fix missing NULL check at remove_events ioctl snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear() unconditionally even if there is no FIFO assigned, and this leads to an Oops due to NULL dereference. The fix is just to add a proper NULL check. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[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: jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols) { Jbig2SymbolDict *new = NULL; if (n_symbols < 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols); return NULL; } new = jbig2_new(ctx, Jbig2SymbolDict, 1); if (new != NULL) { new->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols); new->n_symbols = n_symbols; } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict"); return NULL; } if (new->glyphs != NULL) { memset(new->glyphs, 0, n_symbols * sizeof(Jbig2Image *)); } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict"); jbig2_free(ctx->allocator, new); return NULL; } return new; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: bool V4L2JpegEncodeAccelerator::EncodedInstance::RequestInputBuffers() { DCHECK(parent_->encoder_task_runner_->BelongsToCurrentThread()); struct v4l2_format format; memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; format.fmt.pix_mp.pixelformat = input_buffer_pixelformat_; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_G_FMT, &format); struct v4l2_requestbuffers reqbufs; memset(&reqbufs, 0, sizeof(reqbufs)); reqbufs.count = kBufferCount; reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; reqbufs.memory = V4L2_MEMORY_MMAP; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs); DCHECK(input_buffer_map_.empty()); input_buffer_map_.resize(reqbufs.count); for (size_t i = 0; i < input_buffer_map_.size(); ++i) { free_input_buffers_.push_back(i); struct v4l2_buffer buffer; struct v4l2_plane planes[kMaxI420Plane]; memset(&buffer, 0, sizeof(buffer)); memset(planes, 0, sizeof(planes)); buffer.index = i; buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; buffer.memory = V4L2_MEMORY_MMAP; buffer.m.planes = planes; buffer.length = base::size(planes); IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &buffer); if (input_buffer_num_planes_ != buffer.length) { return false; } for (size_t j = 0; j < buffer.length; ++j) { if (base::checked_cast<int64_t>(planes[j].length) < VideoFrame::PlaneSize( PIXEL_FORMAT_I420, j, gfx::Size(format.fmt.pix_mp.width, format.fmt.pix_mp.height)) .GetArea()) { return false; } void* address = device_->Mmap(NULL, planes[j].length, PROT_READ | PROT_WRITE, MAP_SHARED, planes[j].m.mem_offset); if (address == MAP_FAILED) { VPLOGF(1) << "mmap() failed"; return false; } input_buffer_map_[i].address[j] = address; input_buffer_map_[i].length[j] = planes[j].length; } } return true; } Commit Message: media: remove base::SharedMemoryHandle usage in v4l2 encoder This replaces a use of the legacy UnalignedSharedMemory ctor taking a SharedMemoryHandle with the current ctor taking a PlatformSharedMemoryRegion. Bug: 849207 Change-Id: Iea24ebdcd941cf2fa97e19cf2aeac1a18f9773d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1697602 Commit-Queue: Matthew Cary (CET) <[email protected]> Reviewed-by: Ricky Liang <[email protected]> Cr-Commit-Position: refs/heads/master@{#681740} 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 __init init_elf_binfmt(void) { return register_binfmt(&elf_format); } Commit Message: regset: Prevent null pointer reference on readonly regsets The regset common infrastructure assumed that regsets would always have .get and .set methods, but not necessarily .active methods. Unfortunately people have since written regsets without .set methods. Rather than putting in stub functions everywhere, handle regsets with null .get or .set methods explicitly. Signed-off-by: H. Peter Anvin <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Acked-by: Roland McGrath <[email protected]> Cc: <[email protected]> Signed-off-by: Linus Torvalds <[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: Compositor::Compositor( const viz::FrameSinkId& frame_sink_id, ui::ContextFactory* context_factory, ui::ContextFactoryPrivate* context_factory_private, scoped_refptr<base::SingleThreadTaskRunner> task_runner, bool enable_pixel_canvas, ui::ExternalBeginFrameClient* external_begin_frame_client, bool force_software_compositor, const char* trace_environment_name) : context_factory_(context_factory), context_factory_private_(context_factory_private), frame_sink_id_(frame_sink_id), task_runner_(task_runner), vsync_manager_(new CompositorVSyncManager()), external_begin_frame_client_(external_begin_frame_client), force_software_compositor_(force_software_compositor), layer_animator_collection_(this), is_pixel_canvas_(enable_pixel_canvas), lock_manager_(task_runner), trace_environment_name_(trace_environment_name ? trace_environment_name : kDefaultTraceEnvironmentName), context_creation_weak_ptr_factory_(this) { if (context_factory_private) { auto* host_frame_sink_manager = context_factory_private_->GetHostFrameSinkManager(); host_frame_sink_manager->RegisterFrameSinkId( frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo); host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_, "Compositor"); } root_web_layer_ = cc::Layer::Create(); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); cc::LayerTreeSettings settings; settings.layers_always_allowed_lcd_text = true; settings.use_occlusion_for_tile_prioritization = true; settings.main_frame_before_activation_enabled = false; settings.delegated_sync_points_required = context_factory_->SyncTokensRequiredForDisplayCompositor(); settings.enable_edge_anti_aliasing = false; if (command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders)) { std::string layer_borders_string = command_line->GetSwitchValueASCII( cc::switches::kUIShowCompositedLayerBorders); std::vector<base::StringPiece> entries = base::SplitStringPiece( layer_borders_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (entries.empty()) { settings.initial_debug_state.show_debug_borders.set(); } else { for (const auto& entry : entries) { const struct { const char* name; cc::DebugBorderType type; } kBorders[] = {{cc::switches::kCompositedRenderPassBorders, cc::DebugBorderType::RENDERPASS}, {cc::switches::kCompositedSurfaceBorders, cc::DebugBorderType::SURFACE}, {cc::switches::kCompositedLayerBorders, cc::DebugBorderType::LAYER}}; for (const auto& border : kBorders) { if (border.name == entry) { settings.initial_debug_state.show_debug_borders.set(border.type); break; } } } } } settings.initial_debug_state.show_fps_counter = command_line->HasSwitch(cc::switches::kUIShowFPSCounter); settings.initial_debug_state.show_layer_animation_bounds_rects = command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds); settings.initial_debug_state.show_paint_rects = command_line->HasSwitch(switches::kUIShowPaintRects); settings.initial_debug_state.show_property_changed_rects = command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects); settings.initial_debug_state.show_surface_damage_rects = command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects); settings.initial_debug_state.show_screen_space_rects = command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects); settings.initial_debug_state.SetRecordRenderingStats( command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)); settings.enable_surface_synchronization = true; settings.build_hit_test_data = features::IsVizHitTestingSurfaceLayerEnabled(); settings.use_zero_copy = IsUIZeroCopyEnabled(); settings.use_layer_lists = command_line->HasSwitch(cc::switches::kUIEnableLayerLists); settings.use_partial_raster = !settings.use_zero_copy; settings.use_rgba_4444 = command_line->HasSwitch(switches::kUIEnableRGBA4444Textures); #if defined(OS_MACOSX) settings.resource_settings.use_gpu_memory_buffer_resources = settings.use_zero_copy; settings.enable_elastic_overscroll = true; #endif settings.memory_policy.bytes_limit_when_visible = 512 * 1024 * 1024; if (command_line->HasSwitch( switches::kUiCompositorMemoryLimitWhenVisibleMB)) { std::string value_str = command_line->GetSwitchValueASCII( switches::kUiCompositorMemoryLimitWhenVisibleMB); unsigned value_in_mb; if (base::StringToUint(value_str, &value_in_mb)) { settings.memory_policy.bytes_limit_when_visible = 1024 * 1024 * value_in_mb; } } settings.memory_policy.priority_cutoff_when_visible = gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE; settings.disallow_non_exact_resource_reuse = command_line->HasSwitch(switches::kDisallowNonExactResourceReuse); if (command_line->HasSwitch(switches::kRunAllCompositorStagesBeforeDraw)) { settings.wait_for_all_pipeline_stages_before_draw = true; settings.enable_latency_recovery = false; } if (base::FeatureList::IsEnabled( features::kCompositorThreadedScrollbarScrolling)) { settings.compositor_threaded_scrollbar_scrolling = true; } animation_host_ = cc::AnimationHost::CreateMainInstance(); cc::LayerTreeHost::InitParams params; params.client = this; params.task_graph_runner = context_factory_->GetTaskGraphRunner(); params.settings = &settings; params.main_task_runner = task_runner_; params.mutator_host = animation_host_.get(); host_ = cc::LayerTreeHost::CreateSingleThreaded(this, std::move(params)); if (base::FeatureList::IsEnabled(features::kUiCompositorScrollWithLayers) && host_->GetInputHandler()) { scroll_input_handler_.reset( new ScrollInputHandler(host_->GetInputHandler())); } animation_timeline_ = cc::AnimationTimeline::Create(cc::AnimationIdProvider::NextTimelineId()); animation_host_->AddAnimationTimeline(animation_timeline_.get()); host_->SetHasGpuRasterizationTrigger(features::IsUiGpuRasterizationEnabled()); host_->SetRootLayer(root_web_layer_); host_->SetVisible(true); if (command_line->HasSwitch(switches::kUISlowAnimations)) { slow_animations_ = std::make_unique<ScopedAnimationDurationScaleMode>( ScopedAnimationDurationScaleMode::SLOW_DURATION); } } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} CWE ID: CWE-284 Target: 1 Example 2: Code: _sess_auth_rawntlmssp_assemble_req(struct sess_data *sess_data) { struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; struct cifs_ses *ses = sess_data->ses; __u32 capabilities; char *bcc_ptr; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)pSMB; capabilities = cifs_ssetup_hdr(ses, pSMB); if ((pSMB->req.hdr.Flags2 & SMBFLG2_UNICODE) == 0) { cifs_dbg(VFS, "NTLMSSP requires Unicode support\n"); return -ENOSYS; } pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; capabilities |= CAP_EXTENDED_SECURITY; pSMB->req.Capabilities |= cpu_to_le32(capabilities); bcc_ptr = sess_data->iov[2].iov_base; /* unicode strings must be word aligned */ if ((sess_data->iov[0].iov_len + sess_data->iov[1].iov_len) % 2) { *bcc_ptr = 0; bcc_ptr++; } unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp); sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; return 0; } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <[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 v8::Handle<v8::Value> voidMethodWithArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.voidMethodWithArgs"); if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); imp->voidMethodWithArgs(intArg, strArg, objArg); 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: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static void incomplete_class_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { incomplete_class_message(object, E_NOTICE TSRMLS_CC); } /* }}} */ Commit Message: 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: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tmsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); if((cc0%rowsize)!=0) { TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile", "%s", "(cc0%rowsize)!=0"); return 0; } while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) 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 lo_release(struct gendisk *disk, fmode_t mode) { struct loop_device *lo = disk->private_data; int err; if (atomic_dec_return(&lo->lo_refcnt)) return; mutex_lock(&lo->lo_ctl_mutex); if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) { /* * In autoclear mode, stop the loop thread * and remove configuration after last close. */ err = loop_clr_fd(lo); if (!err) return; } else if (lo->lo_state == Lo_bound) { /* * Otherwise keep thread (if running) and config, * but flush possible ongoing bios in thread. */ blk_mq_freeze_queue(lo->lo_queue); blk_mq_unfreeze_queue(lo->lo_queue); } mutex_unlock(&lo->lo_ctl_mutex); } 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: 1 Example 2: Code: void AdjustNavigateParamsForURL(browser::NavigateParams* params) { if (!params->target_contents && browser::IsURLAllowedInIncognito(params->url)) { Profile* profile = params->browser ? params->browser->profile() : params->profile; if ((profile->IsOffTheRecord() && !Profile::IsGuestSession()) || params->disposition == OFF_THE_RECORD) { profile = profile->GetOriginalProfile(); params->disposition = SINGLETON_TAB; params->profile = profile; params->browser = Browser::GetOrCreateTabbedBrowser(profile); params->window_action = browser::NavigateParams::SHOW_WINDOW; } } } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 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 NavigationControllerImpl::RendererDidNavigateToNewPage( RenderFrameHostImpl* rfh, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, bool is_in_page, bool replace_entry, NavigationHandleImpl* handle) { std::unique_ptr<NavigationEntryImpl> new_entry; bool update_virtual_url = false; if (is_in_page && GetLastCommittedEntry()) { FrameNavigationEntry* frame_entry = new FrameNavigationEntry( params.frame_unique_name, params.item_sequence_number, params.document_sequence_number, rfh->GetSiteInstance(), nullptr, params.url, params.referrer, params.method, params.post_id); new_entry = GetLastCommittedEntry()->CloneAndReplace( frame_entry, true, rfh->frame_tree_node(), delegate_->GetFrameTree()->root()); CHECK(frame_entry->HasOneRef()); update_virtual_url = new_entry->update_virtual_url_with_url(); } if (!new_entry && PendingEntryMatchesHandle(handle) && pending_entry_index_ == -1 && (!pending_entry_->site_instance() || pending_entry_->site_instance() == rfh->GetSiteInstance())) { new_entry = pending_entry_->Clone(); update_virtual_url = new_entry->update_virtual_url_with_url(); new_entry->GetSSL() = handle->ssl_status(); } if (!new_entry) { new_entry = base::WrapUnique(new NavigationEntryImpl); GURL url = params.url; bool needs_update = false; BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary( &url, browser_context_, &needs_update); new_entry->set_update_virtual_url_with_url(needs_update); update_virtual_url = needs_update; new_entry->GetSSL() = handle->ssl_status(); } new_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR : PAGE_TYPE_NORMAL); new_entry->SetURL(params.url); if (update_virtual_url) UpdateVirtualURLToURL(new_entry.get(), params.url); new_entry->SetReferrer(params.referrer); new_entry->SetTransitionType(params.transition); new_entry->set_site_instance( static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance())); new_entry->SetOriginalRequestURL(params.original_request_url); new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent); FrameNavigationEntry* frame_entry = new_entry->GetFrameEntry(rfh->frame_tree_node()); frame_entry->set_frame_unique_name(params.frame_unique_name); frame_entry->set_item_sequence_number(params.item_sequence_number); frame_entry->set_document_sequence_number(params.document_sequence_number); frame_entry->set_method(params.method); frame_entry->set_post_id(params.post_id); if (is_in_page && GetLastCommittedEntry()) { new_entry->SetTitle(GetLastCommittedEntry()->GetTitle()); new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon(); } DCHECK(!params.history_list_was_cleared || !replace_entry); if (params.history_list_was_cleared) { DiscardNonCommittedEntriesInternal(); entries_.clear(); last_committed_entry_index_ = -1; } InsertOrReplaceEntry(std::move(new_entry), replace_entry); } Commit Message: Add DumpWithoutCrashing in RendererDidNavigateToExistingPage This is intended to be reverted after investigating the linked bug. BUG=688425 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2701523004 Cr-Commit-Position: refs/heads/master@{#450900} 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: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; struct sshbuf *b = NULL; int r; const u_char *inblob, *outblob; size_t inl, outl; if ((r = sshbuf_froms(m, &b)) != 0) goto out; if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 || (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0) goto out; if (inl == 0) state->compression_in_started = 0; else if (inl != sizeof(state->compression_in_stream)) { r = SSH_ERR_INTERNAL_ERROR; goto out; } else { state->compression_in_started = 1; memcpy(&state->compression_in_stream, inblob, inl); } if (outl == 0) state->compression_out_started = 0; else if (outl != sizeof(state->compression_out_stream)) { r = SSH_ERR_INTERNAL_ERROR; goto out; } else { state->compression_out_started = 1; memcpy(&state->compression_out_stream, outblob, outl); } r = 0; out: sshbuf_free(b); return r; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119 Target: 1 Example 2: Code: int bio_associate_blkcg(struct bio *bio, struct cgroup_subsys_state *blkcg_css) { if (unlikely(bio->bi_css)) return -EBUSY; css_get(blkcg_css); bio->bi_css = blkcg_css; return 0; } Commit Message: fix unbalanced page refcounting in bio_map_user_iov bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if IO vector has small consecutive buffers belonging to the same page. bio_add_pc_page merges them into one, but the page reference is never dropped. Cc: [email protected] Signed-off-by: Vitaly Mayatskikh <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-772 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 QuicTransportHost::CreateStream( std::unique_ptr<QuicStreamHost> stream_host) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); P2PQuicStream* p2p_stream = quic_transport_->CreateStream(); stream_host->Initialize(this, p2p_stream); stream_hosts_.insert( std::make_pair(stream_host.get(), std::move(stream_host))); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} 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: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp; int i, save_errno; uid_t fsuid; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); save_errno = errno; setfsuid(fsuid); if (fp != NULL) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static int vhost_net_set_features(struct vhost_net *n, u64 features) { size_t vhost_hlen, sock_hlen, hdr_len; int i; hdr_len = (features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr); if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) { /* vhost provides vnet_hdr */ vhost_hlen = hdr_len; sock_hlen = 0; } else { /* socket provides vnet_hdr */ vhost_hlen = 0; sock_hlen = hdr_len; } mutex_lock(&n->dev.mutex); if ((features & (1 << VHOST_F_LOG_ALL)) && !vhost_log_access_ok(&n->dev)) { mutex_unlock(&n->dev.mutex); return -EFAULT; } n->dev.acked_features = features; smp_wmb(); for (i = 0; i < VHOST_NET_VQ_MAX; ++i) { mutex_lock(&n->vqs[i].vq.mutex); n->vqs[i].vhost_hlen = vhost_hlen; n->vqs[i].sock_hlen = sock_hlen; mutex_unlock(&n->vqs[i].vq.mutex); } vhost_net_flush(n); mutex_unlock(&n->dev.mutex); return 0; } Commit Message: vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[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: int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) { if (!m_debug.infile) { int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.infile_name, size); } m_debug.infile = fopen (m_debug.infile_name, "ab"); if (!m_debug.infile) { DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name); m_debug.infile_name[0] = '\0'; return -1; } } if (m_debug.infile && pbuffer && pbuffer->nFilledLen) { unsigned long i, msize; int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width); int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height); unsigned char *pvirt,*ptemp; char *temp = (char *)pbuffer->pBuffer; msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height); if (metadatamode == 1) { pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset); if (pvirt) { ptemp = pvirt; for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } ptemp = pvirt + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } munmap(pvirt, msize); } else if (pvirt == MAP_FAILED) { DEBUG_PRINT_ERROR("%s mmap failed", __func__); return -1; } } else { for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } temp = (char *)pbuffer->pBuffer + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } } } return 0; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 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 crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; struct shash_alg *salg = __crypto_shash_alg(alg); snprintf(rhash.type, CRYPTO_MAX_ALG_NAME, "%s", "shash"); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = salg->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <[email protected]> Cc: Steffen Klassert <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: static int snd_pcm_lib_ioctl_fifo_size(struct snd_pcm_substream *substream, void *arg) { struct snd_pcm_hw_params *params = arg; snd_pcm_format_t format; int channels; ssize_t frame_size; params->fifo_size = substream->runtime->hw.fifo_size; if (!(substream->runtime->hw.info & SNDRV_PCM_INFO_FIFO_IN_FRAMES)) { format = params_format(params); channels = params_channels(params); frame_size = snd_pcm_format_size(format, channels); if (frame_size > 0) params->fifo_size /= (unsigned)frame_size; } return 0; } Commit Message: ALSA: pcm : Call kill_fasync() in stream lock Currently kill_fasync() is called outside the stream lock in snd_pcm_period_elapsed(). This is potentially racy, since the stream may get released even during the irq handler is running. Although snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't guarantee that the irq handler finishes, thus the kill_fasync() call outside the stream spin lock may be invoked after the substream is detached, as recently reported by KASAN. As a quick workaround, move kill_fasync() call inside the stream lock. The fasync is rarely used interface, so this shouldn't have a big impact from the performance POV. Ideally, we should implement some sync mechanism for the proper finish of stream and irq handler. But this oneliner should suffice for most cases, so far. Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Takashi Iwai <[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 init_items(struct MACH0_(obj_t)* bin) { struct load_command lc = {0, 0}; ut8 loadc[sizeof (struct load_command)] = {0}; bool is_first_thread = true; ut64 off = 0LL; int i, len; bin->uuidn = 0; bin->os = 0; bin->has_crypto = 0; if (bin->hdr.sizeofcmds > bin->size) { bprintf ("Warning: chopping hdr.sizeofcmds\n"); bin->hdr.sizeofcmds = bin->size - 128; } for (i = 0, off = sizeof (struct MACH0_(mach_header)); \ i < bin->hdr.ncmds; i++, off += lc.cmdsize) { if (off > bin->size || off + sizeof (struct load_command) > bin->size){ bprintf ("mach0: out of bounds command\n"); return false; } len = r_buf_read_at (bin->b, off, loadc, sizeof (struct load_command)); if (len < 1) { bprintf ("Error: read (lc) at 0x%08"PFMT64x"\n", off); return false; } lc.cmd = r_read_ble32 (&loadc[0], bin->big_endian); lc.cmdsize = r_read_ble32 (&loadc[4], bin->big_endian); if (lc.cmdsize < 1 || off + lc.cmdsize > bin->size) { bprintf ("Warning: mach0_header %d = cmdsize<1.\n", i); break; } sdb_num_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.offset", i), off, 0); sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.format", i), "xd cmd size", 0); switch (lc.cmd) { case LC_DATA_IN_CODE: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "data_in_code", 0); break; case LC_RPATH: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "rpath", 0); break; case LC_SEGMENT_64: case LC_SEGMENT: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "segment", 0); bin->nsegs++; if (!parse_segments (bin, off)) { bprintf ("error parsing segment\n"); bin->nsegs--; return false; } break; case LC_SYMTAB: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "symtab", 0); if (!parse_symtab (bin, off)) { bprintf ("error parsing symtab\n"); return false; } break; case LC_DYSYMTAB: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "dysymtab", 0); if (!parse_dysymtab(bin, off)) { bprintf ("error parsing dysymtab\n"); return false; } break; case LC_DYLIB_CODE_SIGN_DRS: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "dylib_code_sign_drs", 0); break; case LC_VERSION_MIN_MACOSX: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "version_min_macosx", 0); bin->os = 1; break; case LC_VERSION_MIN_IPHONEOS: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "version_min_iphoneos", 0); bin->os = 2; break; case LC_VERSION_MIN_TVOS: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "version_min_tvos", 0); bin->os = 4; break; case LC_VERSION_MIN_WATCHOS: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "version_min_watchos", 0); bin->os = 3; break; case LC_UUID: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "uuid", 0); { struct uuid_command uc = {0}; if (off + sizeof (struct uuid_command) > bin->size) { bprintf ("UUID out of obunds\n"); return false; } if (r_buf_fread_at (bin->b, off, (ut8*)&uc, "24c", 1) != -1) { char key[128]; char val[128]; snprintf (key, sizeof (key)-1, "uuid.%d", bin->uuidn++); r_hex_bin2str ((ut8*)&uc.uuid, 16, val); sdb_set (bin->kv, key, val, 0); } } break; case LC_ENCRYPTION_INFO_64: /* TODO: the struct is probably different here */ case LC_ENCRYPTION_INFO: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "encryption_info", 0); { struct MACH0_(encryption_info_command) eic = {0}; ut8 seic[sizeof (struct MACH0_(encryption_info_command))] = {0}; if (off + sizeof (struct MACH0_(encryption_info_command)) > bin->size) { bprintf ("encryption info out of bounds\n"); return false; } if (r_buf_read_at (bin->b, off, seic, sizeof (struct MACH0_(encryption_info_command))) != -1) { eic.cmd = r_read_ble32 (&seic[0], bin->big_endian); eic.cmdsize = r_read_ble32 (&seic[4], bin->big_endian); eic.cryptoff = r_read_ble32 (&seic[8], bin->big_endian); eic.cryptsize = r_read_ble32 (&seic[12], bin->big_endian); eic.cryptid = r_read_ble32 (&seic[16], bin->big_endian); bin->has_crypto = eic.cryptid; sdb_set (bin->kv, "crypto", "true", 0); sdb_num_set (bin->kv, "cryptid", eic.cryptid, 0); sdb_num_set (bin->kv, "cryptoff", eic.cryptoff, 0); sdb_num_set (bin->kv, "cryptsize", eic.cryptsize, 0); sdb_num_set (bin->kv, "cryptheader", off, 0); } } break; case LC_LOAD_DYLINKER: { sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "dylinker", 0); free (bin->intrp); bin->intrp = NULL; struct dylinker_command dy = {0}; ut8 sdy[sizeof (struct dylinker_command)] = {0}; if (off + sizeof (struct dylinker_command) > bin->size){ bprintf ("Warning: Cannot parse dylinker command\n"); return false; } if (r_buf_read_at (bin->b, off, sdy, sizeof (struct dylinker_command)) == -1) { bprintf ("Warning: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off); } else { dy.cmd = r_read_ble32 (&sdy[0], bin->big_endian); dy.cmdsize = r_read_ble32 (&sdy[4], bin->big_endian); dy.name = r_read_ble32 (&sdy[8], bin->big_endian); int len = dy.cmdsize; char *buf = malloc (len+1); if (buf) { r_buf_read_at (bin->b, off + 0xc, (ut8*)buf, len); buf[len] = 0; free (bin->intrp); bin->intrp = buf; } } } break; case LC_MAIN: { struct { ut64 eo; ut64 ss; } ep = {0}; ut8 sep[2 * sizeof (ut64)] = {0}; sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "main", 0); if (!is_first_thread) { bprintf("Error: LC_MAIN with other threads\n"); return false; } if (off + 8 > bin->size || off + sizeof (ep) > bin->size) { bprintf ("invalid command size for main\n"); return false; } r_buf_read_at (bin->b, off + 8, sep, 2 * sizeof (ut64)); ep.eo = r_read_ble64 (&sep[0], bin->big_endian); ep.ss = r_read_ble64 (&sep[8], bin->big_endian); bin->entry = ep.eo; bin->main_cmd = lc; sdb_num_set (bin->kv, "mach0.entry.offset", off + 8, 0); sdb_num_set (bin->kv, "stacksize", ep.ss, 0); is_first_thread = false; } break; case LC_UNIXTHREAD: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "unixthread", 0); if (!is_first_thread) { bprintf("Error: LC_UNIXTHREAD with other threads\n"); return false; } case LC_THREAD: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "thread", 0); if (!parse_thread (bin, &lc, off, is_first_thread)) { bprintf ("Cannot parse thread\n"); return false; } is_first_thread = false; break; case LC_LOAD_DYLIB: case LC_LOAD_WEAK_DYLIB: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "load_dylib", 0); bin->nlibs++; if (!parse_dylib(bin, off)){ bprintf ("Cannot parse dylib\n"); bin->nlibs--; return false; } break; case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: { ut8 dyldi[sizeof (struct dyld_info_command)] = {0}; sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "dyld_info", 0); bin->dyld_info = malloc (sizeof(struct dyld_info_command)); if (off + sizeof (struct dyld_info_command) > bin->size){ bprintf ("Cannot parse dyldinfo\n"); free (bin->dyld_info); return false; } if (r_buf_read_at (bin->b, off, dyldi, sizeof (struct dyld_info_command)) == -1) { free (bin->dyld_info); bin->dyld_info = NULL; bprintf ("Error: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off); } else { bin->dyld_info->cmd = r_read_ble32 (&dyldi[0], bin->big_endian); bin->dyld_info->cmdsize = r_read_ble32 (&dyldi[4], bin->big_endian); bin->dyld_info->rebase_off = r_read_ble32 (&dyldi[8], bin->big_endian); bin->dyld_info->rebase_size = r_read_ble32 (&dyldi[12], bin->big_endian); bin->dyld_info->bind_off = r_read_ble32 (&dyldi[16], bin->big_endian); bin->dyld_info->bind_size = r_read_ble32 (&dyldi[20], bin->big_endian); bin->dyld_info->weak_bind_off = r_read_ble32 (&dyldi[24], bin->big_endian); bin->dyld_info->weak_bind_size = r_read_ble32 (&dyldi[28], bin->big_endian); bin->dyld_info->lazy_bind_off = r_read_ble32 (&dyldi[32], bin->big_endian); bin->dyld_info->lazy_bind_size = r_read_ble32 (&dyldi[36], bin->big_endian); bin->dyld_info->export_off = r_read_ble32 (&dyldi[40], bin->big_endian); bin->dyld_info->export_size = r_read_ble32 (&dyldi[44], bin->big_endian); } } break; case LC_CODE_SIGNATURE: parse_signature (bin, off); sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "signature", 0); /* ut32 dataoff break; case LC_SOURCE_VERSION: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "version", 0); /* uint64_t version; */ /* A.B.C.D.E packed as a24.b10.c10.d10.e10 */ break; case LC_SEGMENT_SPLIT_INFO: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "split_info", 0); /* TODO */ break; case LC_FUNCTION_STARTS: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "function_starts", 0); if (!parse_function_starts (bin, off)) { bprintf ("Cannot parse LC_FUNCTION_STARTS\n"); } break; case LC_REEXPORT_DYLIB: sdb_set (bin->kv, sdb_fmt (0, "mach0_cmd_%d.cmd", i), "dylib", 0); /* TODO */ break; default: break; } } return true; } Commit Message: Fix null deref and uaf in mach0 parser 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: void WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); delegate_->OnSentData(socket, amount_sent); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::SendPending)); } } 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: 1 Example 2: Code: PassRefPtrWillBeRawPtr<FilterEffect> SVGFEColorMatrixElement::build(SVGFilterBuilder* filterBuilder, Filter* filter) { FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value())); if (!input1) return nullptr; Vector<float> filterValues; ColorMatrixType filterType = m_type->currentValue()->enumValue(); if (!hasAttribute(SVGNames::valuesAttr)) { switch (filterType) { case FECOLORMATRIX_TYPE_MATRIX: for (size_t i = 0; i < 20; i++) filterValues.append((i % 6) ? 0 : 1); break; case FECOLORMATRIX_TYPE_HUEROTATE: filterValues.append(0); break; case FECOLORMATRIX_TYPE_SATURATE: filterValues.append(1); break; default: break; } } else { RefPtrWillBeRawPtr<SVGNumberList> values = m_values->currentValue(); size_t size = values->length(); if ((filterType == FECOLORMATRIX_TYPE_MATRIX && size != 20) || (filterType == FECOLORMATRIX_TYPE_HUEROTATE && size != 1) || (filterType == FECOLORMATRIX_TYPE_SATURATE && size != 1)) return nullptr; filterValues = values->toFloatVector(); } RefPtrWillBeRawPtr<FilterEffect> effect = FEColorMatrix::create(filter, filterType, filterValues); effect->inputEffects().append(input1); return effect.release(); } Commit Message: Explicitly enforce values size in feColorMatrix. [email protected] BUG=468519 Review URL: https://codereview.chromium.org/1075413002 git-svn-id: svn://svn.chromium.org/blink/trunk@193571 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 nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh, char **target) { uint32_t data[1024]; uint32_t *p; uint32_t len; struct packet *nfs_packet; /* * struct READLINK3args { * nfs_fh3 symlink; * }; * * struct READLINK3resok { * post_op_attr symlink_attributes; * nfspath3 data; * }; * * struct READLINK3resfail { * post_op_attr symlink_attributes; * } * * union READLINK3res switch (nfsstat3 status) { * case NFS3_OK: * READLINK3resok resok; * default: * READLINK3resfail resfail; * }; */ p = &(data[0]); p = rpc_add_credentials(p); p = nfs_add_fh3(p, fh); len = p - &(data[0]); nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; p = nfs_read_post_op_attr(p, NULL); len = ntoh32(net_read_uint32(p)); /* new path length */ p++; *target = xzalloc(len + 1); return 0; } 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: gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += ( map->rows - 1 ) * map->pitch; for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: void Browser::OnWindowDidShow() { if (window_has_shown_) return; window_has_shown_ = true; startup_metric_utils::RecordBrowserWindowDisplay(base::TimeTicks::Now()); if (!is_type_tabbed() || window_->IsMinimized()) return; GlobalErrorService* service = GlobalErrorServiceFactory::GetForProfile(profile()); GlobalError* error = service->GetFirstGlobalErrorWithBubbleView(); if (error) error->ShowBubbleView(this); } Commit Message: Don't focus the location bar for NTP navigations in non-selected tabs. BUG=677716 TEST=See bug for repro steps. Review-Url: https://codereview.chromium.org/2624373002 Cr-Commit-Position: refs/heads/master@{#443338} 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: onig_new_without_alloc(regex_t* reg, const UChar* pattern, const UChar* pattern_end, OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax, OnigErrorInfo* einfo) { int r; r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax); if (r != 0) return r; r = onig_compile(reg, pattern, pattern_end, einfo); return r; } Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode. 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: static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg) { char fnam[PROCLEN]; FILE *f; bool answer = false; char *line = NULL; size_t len = 0; int ret; ret = snprintf(fnam, PROCLEN, "/proc/%d/cgroup", pid); if (ret < 0 || ret >= PROCLEN) return false; if (!(f = fopen(fnam, "r"))) return false; while (getline(&line, &len, f) != -1) { char *c1, *c2, *linecmp; if (!line[0]) continue; c1 = strchr(line, ':'); if (!c1) goto out; c1++; c2 = strchr(c1, ':'); if (!c2) goto out; *c2 = '\0'; if (strcmp(c1, contrl) != 0) continue; c2++; stripnewline(c2); prune_init_slice(c2); /* * callers pass in '/' for root cgroup, otherwise they pass * in a cgroup without leading '/' */ linecmp = *cg == '/' ? c2 : c2+1; if (strncmp(linecmp, cg, strlen(linecmp)) != 0) { if (nextcg) *nextcg = get_next_cgroup_dir(linecmp, cg); goto out; } answer = true; goto out; } out: fclose(f); free(line); return answer; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static inline zend_long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { zend_long elements; if( *p >= max - 2) { zend_error(E_WARNING, "Bad unserialize data"); return -1; } elements = parse_iv2((*p) + 2, p); (*p) += 2; if (ce->serialize == NULL) { object_init_ex(rval, ce); } else { /* If this class implements Serializable, it should not land here but in object_custom(). The passed string obviously doesn't descend from the regular serializer. */ zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ZSTR_VAL(ce->name)); return -1; } return elements; } Commit Message: Fixed bug #74103 and bug #75054 Directly fail unserialization when trying to acquire an r/R reference to an UNDEF HT slot. Previously this left an UNDEF and later deleted the index/key from the HT. What actually caused the issue here is a combination of two factors: First, the key deletion was performed using the hash API, rather than the symtable API, such that the element was not actually removed if it used an integral string key. Second, a subsequent deletion operation, while collecting trailing UNDEF ranges, would mark the element as available for reuse (leaving a corrupted HT state with nNumOfElemnts > nNumUsed). Fix this by failing early and dropping the deletion code. 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionRemoveEventListener(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() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); 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 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: do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc=0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* If we use the undocumented feature to suppress * the zlib header, we have to give inflate an * extra dummy byte to read */ if( nread < count && zfx->algo == 1 ) { *(zfx->inbuf + n) = 0xFF; /* is it really needed ? */ zfx->algo1hack = 1; n++; } zs->avail_in = n; } log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while( zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR ); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } 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: 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: apr_status_t h2_session_stream_done(h2_session *session, h2_stream *stream) { ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, session->c, "h2_stream(%ld-%d): EOS bucket cleanup -> done", session->id, stream->id); h2_mplx_stream_done(session->mplx, stream); dispatch_event(session, H2_SESSION_EV_STREAM_DONE, 0, NULL); return APR_SUCCESS; } Commit Message: SECURITY: CVE-2016-8740 mod_http2: properly crafted, endless HTTP/2 CONTINUATION frames could be used to exhaust all server's memory. Reported by: Naveen Tiwari <[email protected]> and CDF/SEFCOM at Arizona State University git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1772576 13f79535-47bb-0310-9956-ffa450edef68 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: int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; struct sockaddr_in *sin; struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); if (msg_flags & MSG_OOB) goto out; while (1) { /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } break; } if (inc) rds_inc_put(inc); out: return ret; } Commit Message: rds: set correct msg_namelen Jay Fenlason ([email protected]) found a bug, that recvfrom() on an RDS socket can return the contents of random kernel memory to userspace if it was called with a address length larger than sizeof(struct sockaddr_in). rds_recvmsg() also fails to set the addr_len paramater properly before returning, but that's just a bug. There are also a number of cases wher recvfrom() can return an entirely bogus address. Anything in rds_recvmsg() that returns a non-negative value but does not go through the "sin = (struct sockaddr_in *)msg->msg_name;" code path at the end of the while(1) loop will return up to 128 bytes of kernel memory to userspace. And I write two test programs to reproduce this bug, you will see that in rds_server, fromAddr will be overwritten and the following sock_fd will be destroyed. Yes, it is the programmer's fault to set msg_namelen incorrectly, but it is better to make the kernel copy the real length of address to user space in such case. How to run the test programs ? I test them on 32bit x86 system, 3.5.0-rc7. 1 compile gcc -o rds_client rds_client.c gcc -o rds_server rds_server.c 2 run ./rds_server on one console 3 run ./rds_client on another console 4 you will see something like: server is waiting to receive data... old socket fd=3 server received data from client:data from client msg.msg_namelen=32 new socket fd=-1067277685 sendmsg() : Bad file descriptor /***************** rds_client.c ********************/ int main(void) { int sock_fd; struct sockaddr_in serverAddr; struct sockaddr_in toAddr; char recvBuffer[128] = "data from client"; struct msghdr msg; struct iovec iov; sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0); if (sock_fd < 0) { perror("create socket error\n"); exit(1); } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddr.sin_port = htons(4001); if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("bind() error\n"); close(sock_fd); exit(1); } memset(&toAddr, 0, sizeof(toAddr)); toAddr.sin_family = AF_INET; toAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); toAddr.sin_port = htons(4000); msg.msg_name = &toAddr; msg.msg_namelen = sizeof(toAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = strlen(recvBuffer) + 1; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; if (sendmsg(sock_fd, &msg, 0) == -1) { perror("sendto() error\n"); close(sock_fd); exit(1); } printf("client send data:%s\n", recvBuffer); memset(recvBuffer, '\0', 128); msg.msg_name = &toAddr; msg.msg_namelen = sizeof(toAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = 128; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; if (recvmsg(sock_fd, &msg, 0) == -1) { perror("recvmsg() error\n"); close(sock_fd); exit(1); } printf("receive data from server:%s\n", recvBuffer); close(sock_fd); return 0; } /***************** rds_server.c ********************/ int main(void) { struct sockaddr_in fromAddr; int sock_fd; struct sockaddr_in serverAddr; unsigned int addrLen; char recvBuffer[128]; struct msghdr msg; struct iovec iov; sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0); if(sock_fd < 0) { perror("create socket error\n"); exit(0); } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddr.sin_port = htons(4000); if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("bind error\n"); close(sock_fd); exit(1); } printf("server is waiting to receive data...\n"); msg.msg_name = &fromAddr; /* * I add 16 to sizeof(fromAddr), ie 32, * and pay attention to the definition of fromAddr, * recvmsg() will overwrite sock_fd, * since kernel will copy 32 bytes to userspace. * * If you just use sizeof(fromAddr), it works fine. * */ msg.msg_namelen = sizeof(fromAddr) + 16; /* msg.msg_namelen = sizeof(fromAddr); */ msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = 128; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; while (1) { printf("old socket fd=%d\n", sock_fd); if (recvmsg(sock_fd, &msg, 0) == -1) { perror("recvmsg() error\n"); close(sock_fd); exit(1); } printf("server received data from client:%s\n", recvBuffer); printf("msg.msg_namelen=%d\n", msg.msg_namelen); printf("new socket fd=%d\n", sock_fd); strcat(recvBuffer, "--data from server"); if (sendmsg(sock_fd, &msg, 0) == -1) { perror("sendmsg()\n"); close(sock_fd); exit(1); } } close(sock_fd); return 0; } Signed-off-by: Weiping Pan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: const FeatureEntry* GetFeatureEntries(size_t* count) { if (!GetEntriesForTesting()->empty()) { *count = GetEntriesForTesting()->size(); return GetEntriesForTesting()->data(); } *count = base::size(kFeatureEntries); return kFeatureEntries; } Commit Message: Add feature and flag to enable incognito Chrome Custom Tabs kCCTIncognito feature and flag are added to enable/disable incognito Chrome Custom Tabs. The default is set to disabled. Bug: 1023759 Change-Id: If32d256e3e9eaa94bcc09f7538c85e2dab53c589 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1911201 Reviewed-by: Peter Conn <[email protected]> Reviewed-by: David Trainor <[email protected]> Commit-Queue: Ramin Halavati <[email protected]> Cr-Commit-Position: refs/heads/master@{#714849} 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: ProcEstablishConnection(ClientPtr client) { const char *reason; char *auth_proto, *auth_string; xConnClientPrefix *prefix; REQUEST(xReq); prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq); auth_proto = (char *) prefix + sz_xConnClientPrefix; auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto); if ((prefix->majorVersion != X_PROTOCOL) || (prefix->minorVersion != X_PROTOCOL_REVISION)) reason = "Protocol version mismatch"; else return (SendConnSetup(client, reason)); } Commit Message: 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: void NTPResourceCache::CreateNewTabHTML() { DictionaryValue localized_strings; localized_strings.SetString("bookmarkbarattached", profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ? "true" : "false"); localized_strings.SetString("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION) ? "true" : "false"); localized_strings.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); localized_strings.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); localized_strings.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); localized_strings.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); localized_strings.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); localized_strings.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); localized_strings.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); localized_strings.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); localized_strings.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); localized_strings.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); localized_strings.SetString("appuninstall", l10n_util::GetStringFUTF16( IDS_EXTENSIONS_UNINSTALL, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); localized_strings.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); localized_strings.SetString("appdisablenotifications", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS)); localized_strings.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); localized_strings.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); localized_strings.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); localized_strings.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); localized_strings.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); localized_strings.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); localized_strings.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); localized_strings.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); #if defined(OS_CHROMEOS) localized_strings.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings); NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings); if (profile_->GetProfileSyncService()) localized_strings.SetString("syncispresent", "true"); else localized_strings.SetString("syncispresent", "false"); ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); std::string anim = ui::Animation::ShouldRenderRichAnimation() ? "true" : "false"; localized_strings.SetString("anim", anim); int alignment; ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment); localized_strings.SetString("themegravity", (alignment & ThemeService::ALIGN_RIGHT) ? "right" : ""); if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) && profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) { localized_strings.SetString("customlogo", InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart), profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ? "true" : "false"); } else { localized_strings.SetString("customlogo", "false"); } if (PromoResourceService::CanShowNotificationPromo(profile_)) { localized_strings.SetString("serverpromo", profile_->GetPrefs()->GetString(prefs::kNTPPromoLine)); } std::string full_html; base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html, &localized_strings); new_tab_html_ = base::RefCountedString::TakeString(&full_html); } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void xhci_detach(USBPort *usbport) { XHCIState *xhci = usbport->opaque; XHCIPort *port = xhci_lookup_port(xhci, usbport); xhci_detach_slot(xhci, usbport); xhci_port_update(port, 1); } Commit Message: CWE ID: CWE-835 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: Document* Document::Create(Document& document) { Document* new_document = new Document( DocumentInit::Create().WithContextDocument(&document).WithURL( BlankURL())); new_document->SetSecurityOrigin(document.GetMutableSecurityOrigin()); new_document->SetContextFeatures(document.GetContextFeatures()); return new_document; } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#597889} 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: PrintPreviewUI::~PrintPreviewUI() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); g_print_preview_request_id_map.Get().Erase(preview_ui_addr_str_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: static void ims_pcu_process_async_firmware(const struct firmware *fw, void *context) { struct ims_pcu *pcu = context; int error; if (!fw) { dev_err(pcu->dev, "Failed to get firmware %s\n", IMS_PCU_FIRMWARE_NAME); goto out; } error = ihex_validate_fw(fw); if (error) { dev_err(pcu->dev, "Firmware %s is invalid\n", IMS_PCU_FIRMWARE_NAME); goto out; } mutex_lock(&pcu->cmd_mutex); ims_pcu_handle_firmware_update(pcu, fw); mutex_unlock(&pcu->cmd_mutex); release_firmware(fw); out: complete(&pcu->async_firmware_done); } Commit Message: Input: ims-pcu - sanity check against missing interfaces A malicious device missing interface can make the driver oops. Add sanity checking. Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Dmitry Torokhov <[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: int PreProcessingFx_ProcessReverse(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer) { preproc_effect_t * effect = (preproc_effect_t *)self; int status = 0; if (effect == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL"); return -EINVAL; } preproc_session_t * session = (preproc_session_t *)effect->session; if (inBuffer == NULL || inBuffer->raw == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer"); return -EINVAL; } session->revProcessedMsk |= (1<<effect->procId); if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) { effect->session->revProcessedMsk = 0; if (session->revResampler != NULL) { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } if (session->revBufSize < session->framesRev + fr) { session->revBufSize = session->framesRev + fr; session->revBuf = (int16_t *)realloc(session->revBuf, session->revBufSize * session->inChannelCount * sizeof(int16_t)); } memcpy(session->revBuf + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } spx_uint32_t frIn = session->framesRev; spx_uint32_t frOut = session->apmFrameCount; if (session->inChannelCount == 1) { speex_resampler_process_int(session->revResampler, 0, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } else { speex_resampler_process_interleaved_int(session->revResampler, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } memcpy(session->revBuf, session->revBuf + frIn * session->inChannelCount, (session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t)); session->framesRev -= frIn; } else { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } session->framesRev = 0; } session->revFrame->_payloadDataLengthInSamples = session->apmFrameCount * session->inChannelCount; effect->session->apm->AnalyzeReverseStream(session->revFrame); return 0; } else { return -ENODATA; } } 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 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: status_t CameraClient::dump(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264 Target: 1 Example 2: Code: bitoverlay_no_len(PG_FUNCTION_ARGS) { VarBit *t1 = PG_GETARG_VARBIT_P(0); VarBit *t2 = PG_GETARG_VARBIT_P(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl; sl = VARBITLEN(t2); /* defaults to length(t2) */ PG_RETURN_VARBIT_P(bit_overlay(t1, t2, sp, sl)); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 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: void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, bool fullmm) { tlb->mm = mm; tlb->fullmm = fullmm; tlb->need_flush_all = 0; tlb->start = -1UL; tlb->end = 0; tlb->need_flush = 0; tlb->fast_mode = (num_possible_cpus() == 1); tlb->local.next = NULL; tlb->local.nr = 0; tlb->local.max = ARRAY_SIZE(tlb->__pages); tlb->active = &tlb->local; tlb->batch_count = 0; #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb->batch = NULL; #endif } Commit Message: vm: add vm_iomap_memory() helper function Various drivers end up replicating the code to mmap() their memory buffers into user space, and our core memory remapping function may be very flexible but it is unnecessarily complicated for the common cases to use. Our internal VM uses pfn's ("page frame numbers") which simplifies things for the VM, and allows us to pass physical addresses around in a denser and more efficient format than passing a "phys_addr_t" around, and having to shift it up and down by the page size. But it just means that drivers end up doing that shifting instead at the interface level. It also means that drivers end up mucking around with internal VM things like the vma details (vm_pgoff, vm_start/end) way more than they really need to. So this just exports a function to map a certain physical memory range into user space (using a phys_addr_t based interface that is much more natural for a driver) and hides all the complexity from the driver. Some drivers will still end up tweaking the vm_page_prot details for things like prefetching or cacheability etc, but that's actually relevant to the driver, rather than caring about what the page offset of the mapping is into the particular IO memory region. Acked-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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> V8Proxy::throwNotEnoughArgumentsError() { return throwError(TypeError, "Not enough arguments"); } 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 AppCacheHost::PrepareForTransfer() { DCHECK(!associated_cache()); DCHECK(!is_selection_pending()); DCHECK(!group_being_updated_.get()); host_id_ = kAppCacheNoHostId; frontend_ = NULL; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} 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 webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height) { if (!webkitWebViewBase->priv->inspectorView) return; if (webkitWebViewBase->priv->inspectorViewHeight == height) return; webkitWebViewBase->priv->inspectorViewHeight = height; gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase)); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port) { char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT }; char *s; struct kex *kex; int r; xxx_host = host; xxx_hostaddr = hostaddr; if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL) fatal("%s: kex_names_cat", __func__); myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s); myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(options.ciphers); myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(options.ciphers); myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ? "[email protected],zlib,none" : "none,[email protected],zlib"; myproposal[PROPOSAL_MAC_ALGS_CTOS] = myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; if (options.hostkeyalgorithms != NULL) { if (kex_assemble_names(KEX_DEFAULT_PK_ALG, &options.hostkeyalgorithms) != 0) fatal("%s: kex_assemble_namelist", __func__); myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(options.hostkeyalgorithms); } else { /* Enforce default */ options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG); /* Prefer algorithms that we already have keys for */ myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( order_hostkeyalgs(host, hostaddr, port)); } if (options.rekey_limit || options.rekey_interval) packet_set_rekey_limits((u_int32_t)options.rekey_limit, (time_t)options.rekey_interval); /* start key exchange */ if ((r = kex_setup(active_state, myproposal)) != 0) fatal("kex_setup: %s", ssh_err(r)); kex = active_state->kex; #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client; kex->kex[KEX_DH_GEX_SHA1] = kexgex_client; kex->kex[KEX_DH_GEX_SHA256] = kexgex_client; kex->kex[KEX_ECDH_SHA2] = kexecdh_client; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_client; kex->client_version_string=client_version_string; kex->server_version_string=server_version_string; kex->verify_host_key=&verify_host_key_callback; dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); /* remove ext-info from the KEX proposals for rekeying */ myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(options.kex_algorithms); if ((r = kex_prop2buf(kex->my, myproposal)) != 0) fatal("kex_prop2buf: %s", ssh_err(r)); session_id2 = kex->session_id; session_id2_len = kex->session_id_len; #ifdef DEBUG_KEXDH /* send 1st encrypted/maced/compressed message */ packet_start(SSH2_MSG_IGNORE); packet_put_cstring("markus"); packet_send(); packet_write_wait(); #endif } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119 Target: 1 Example 2: Code: gst_asf_demux_get_guid (ASFGuid * guid, guint8 ** p_data, guint64 * p_size) { g_assert (*p_size >= 4 * sizeof (guint32)); guid->v1 = gst_asf_demux_get_uint32 (p_data, p_size); guid->v2 = gst_asf_demux_get_uint32 (p_data, p_size); guid->v3 = gst_asf_demux_get_uint32 (p_data, p_size); guid->v4 = gst_asf_demux_get_uint32 (p_data, p_size); } Commit Message: asfdemux: Check that we have enough data available before parsing bool/uint extended content descriptors https://bugzilla.gnome.org/show_bug.cgi?id=777955 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: static EVP_MD * php_openssl_get_evp_md_from_algo(long algo) { /* {{{ */ EVP_MD *mdtype; switch (algo) { case OPENSSL_ALGO_SHA1: mdtype = (EVP_MD *) EVP_sha1(); break; case OPENSSL_ALGO_MD5: mdtype = (EVP_MD *) EVP_md5(); break; case OPENSSL_ALGO_MD4: mdtype = (EVP_MD *) EVP_md4(); break; #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: mdtype = (EVP_MD *) EVP_md2(); break; #endif case OPENSSL_ALGO_DSS1: mdtype = (EVP_MD *) EVP_dss1(); break; #if OPENSSL_VERSION_NUMBER >= 0x0090708fL case OPENSSL_ALGO_SHA224: mdtype = (EVP_MD *) EVP_sha224(); break; case OPENSSL_ALGO_SHA256: mdtype = (EVP_MD *) EVP_sha256(); break; case OPENSSL_ALGO_SHA384: mdtype = (EVP_MD *) EVP_sha384(); break; case OPENSSL_ALGO_SHA512: mdtype = (EVP_MD *) EVP_sha512(); break; case OPENSSL_ALGO_RMD160: mdtype = (EVP_MD *) EVP_ripemd160(); break; #endif default: return NULL; break; } return mdtype; } /* }}} */ 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: OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(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: bool HevcParameterSets::findParam64(uint32_t key, uint64_t *param) { return findParam(key, param, mParams); } Commit Message: Validate lengths in HEVC metadata parsing Add code to validate the size parameter passed to HecvParameterSets::addNalUnit(). Previously vulnerable to decrementing an unsigned past 0, yielding a huge result value. Bug: 35467107 Test: ran POC, no crash, emitted new "bad length" log entry Change-Id: Ia169b9edc1e0f7c5302e3c68aa90a54e8863d79e (cherry picked from commit e0dcf097cc029d056926029a29419e1650cbdf1b) 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: int main(int argc, char **argv) { FILE *infile, *outfile[NUM_ENCODERS]; vpx_codec_ctx_t codec[NUM_ENCODERS]; vpx_codec_enc_cfg_t cfg[NUM_ENCODERS]; vpx_codec_pts_t frame_cnt = 0; vpx_image_t raw[NUM_ENCODERS]; vpx_codec_err_t res[NUM_ENCODERS]; int i; long width; long height; int frame_avail; int got_data; int flags = 0; /*Currently, only realtime mode is supported in multi-resolution encoding.*/ int arg_deadline = VPX_DL_REALTIME; /* Set show_psnr to 1/0 to show/not show PSNR. Choose show_psnr=0 if you don't need to know PSNR, which will skip PSNR calculation and save encoding time. */ int show_psnr = 0; uint64_t psnr_sse_total[NUM_ENCODERS] = {0}; uint64_t psnr_samples_total[NUM_ENCODERS] = {0}; double psnr_totals[NUM_ENCODERS][4] = {{0,0}}; int psnr_count[NUM_ENCODERS] = {0}; /* Set the required target bitrates for each resolution level. * If target bitrate for highest-resolution level is set to 0, * (i.e. target_bitrate[0]=0), we skip encoding at that level. */ unsigned int target_bitrate[NUM_ENCODERS]={1000, 500, 100}; /* Enter the frame rate of the input video */ int framerate = 30; /* Set down-sampling factor for each resolution level. dsf[0] controls down sampling from level 0 to level 1; dsf[1] controls down sampling from level 1 to level 2; dsf[2] is not used. */ vpx_rational_t dsf[NUM_ENCODERS] = {{2, 1}, {2, 1}, {1, 1}}; if(argc!= (5+NUM_ENCODERS)) die("Usage: %s <width> <height> <infile> <outfile(s)> <output psnr?>\n", argv[0]); printf("Using %s\n",vpx_codec_iface_name(interface)); width = strtol(argv[1], NULL, 0); height = strtol(argv[2], NULL, 0); if(width < 16 || width%2 || height <16 || height%2) die("Invalid resolution: %ldx%ld", width, height); /* Open input video file for encoding */ if(!(infile = fopen(argv[3], "rb"))) die("Failed to open %s for reading", argv[3]); /* Open output file for each encoder to output bitstreams */ for (i=0; i< NUM_ENCODERS; i++) { if(!target_bitrate[i]) { outfile[i] = NULL; continue; } if(!(outfile[i] = fopen(argv[i+4], "wb"))) die("Failed to open %s for writing", argv[i+4]); } show_psnr = strtol(argv[NUM_ENCODERS + 4], NULL, 0); /* Populate default encoder configuration */ for (i=0; i< NUM_ENCODERS; i++) { res[i] = vpx_codec_enc_config_default(interface, &cfg[i], 0); if(res[i]) { printf("Failed to get config: %s\n", vpx_codec_err_to_string(res[i])); return EXIT_FAILURE; } } /* * Update the default configuration according to needs of the application. */ /* Highest-resolution encoder settings */ cfg[0].g_w = width; cfg[0].g_h = height; cfg[0].g_threads = 1; /* number of threads used */ cfg[0].rc_dropframe_thresh = 30; cfg[0].rc_end_usage = VPX_CBR; cfg[0].rc_resize_allowed = 0; cfg[0].rc_min_quantizer = 4; cfg[0].rc_max_quantizer = 56; cfg[0].rc_undershoot_pct = 98; cfg[0].rc_overshoot_pct = 100; cfg[0].rc_buf_initial_sz = 500; cfg[0].rc_buf_optimal_sz = 600; cfg[0].rc_buf_sz = 1000; cfg[0].g_error_resilient = 1; /* Enable error resilient mode */ cfg[0].g_lag_in_frames = 0; /* Disable automatic keyframe placement */ /* Note: These 3 settings are copied to all levels. But, except the lowest * resolution level, all other levels are set to VPX_KF_DISABLED internally. */ cfg[0].kf_min_dist = 3000; cfg[0].kf_max_dist = 3000; cfg[0].rc_target_bitrate = target_bitrate[0]; /* Set target bitrate */ cfg[0].g_timebase.num = 1; /* Set fps */ cfg[0].g_timebase.den = framerate; /* Other-resolution encoder settings */ for (i=1; i< NUM_ENCODERS; i++) { memcpy(&cfg[i], &cfg[0], sizeof(vpx_codec_enc_cfg_t)); cfg[i].g_threads = 1; /* number of threads used */ cfg[i].rc_target_bitrate = target_bitrate[i]; /* Note: Width & height of other-resolution encoders are calculated * from the highest-resolution encoder's size and the corresponding * down_sampling_factor. */ { unsigned int iw = cfg[i-1].g_w*dsf[i-1].den + dsf[i-1].num - 1; unsigned int ih = cfg[i-1].g_h*dsf[i-1].den + dsf[i-1].num - 1; cfg[i].g_w = iw/dsf[i-1].num; cfg[i].g_h = ih/dsf[i-1].num; } /* Make width & height to be multiplier of 2. */ if((cfg[i].g_w)%2)cfg[i].g_w++; if((cfg[i].g_h)%2)cfg[i].g_h++; } /* Allocate image for each encoder */ for (i=0; i< NUM_ENCODERS; i++) if(!vpx_img_alloc(&raw[i], VPX_IMG_FMT_I420, cfg[i].g_w, cfg[i].g_h, 32)) die("Failed to allocate image", cfg[i].g_w, cfg[i].g_h); if (raw[0].stride[VPX_PLANE_Y] == raw[0].d_w) read_frame_p = read_frame; else read_frame_p = read_frame_by_row; for (i=0; i< NUM_ENCODERS; i++) if(outfile[i]) write_ivf_file_header(outfile[i], &cfg[i], 0); /* Initialize multi-encoder */ if(vpx_codec_enc_init_multi(&codec[0], interface, &cfg[0], NUM_ENCODERS, (show_psnr ? VPX_CODEC_USE_PSNR : 0), &dsf[0])) die_codec(&codec[0], "Failed to initialize encoder"); /* The extra encoding configuration parameters can be set as follows. */ /* Set encoding speed */ for ( i=0; i<NUM_ENCODERS; i++) { int speed = -6; if(vpx_codec_control(&codec[i], VP8E_SET_CPUUSED, speed)) die_codec(&codec[i], "Failed to set cpu_used"); } /* Set static threshold. */ for ( i=0; i<NUM_ENCODERS; i++) { unsigned int static_thresh = 1; if(vpx_codec_control(&codec[i], VP8E_SET_STATIC_THRESHOLD, static_thresh)) die_codec(&codec[i], "Failed to set static threshold"); } /* Set NOISE_SENSITIVITY to do TEMPORAL_DENOISING */ /* Enable denoising for the highest-resolution encoder. */ if(vpx_codec_control(&codec[0], VP8E_SET_NOISE_SENSITIVITY, 1)) die_codec(&codec[0], "Failed to set noise_sensitivity"); for ( i=1; i< NUM_ENCODERS; i++) { if(vpx_codec_control(&codec[i], VP8E_SET_NOISE_SENSITIVITY, 0)) die_codec(&codec[i], "Failed to set noise_sensitivity"); } frame_avail = 1; got_data = 0; while(frame_avail || got_data) { vpx_codec_iter_t iter[NUM_ENCODERS]={NULL}; const vpx_codec_cx_pkt_t *pkt[NUM_ENCODERS]; flags = 0; frame_avail = read_frame_p(infile, &raw[0]); if(frame_avail) { for ( i=1; i<NUM_ENCODERS; i++) { /*Scale the image down a number of times by downsampling factor*/ /* FilterMode 1 or 2 give better psnr than FilterMode 0. */ I420Scale(raw[i-1].planes[VPX_PLANE_Y], raw[i-1].stride[VPX_PLANE_Y], raw[i-1].planes[VPX_PLANE_U], raw[i-1].stride[VPX_PLANE_U], raw[i-1].planes[VPX_PLANE_V], raw[i-1].stride[VPX_PLANE_V], raw[i-1].d_w, raw[i-1].d_h, raw[i].planes[VPX_PLANE_Y], raw[i].stride[VPX_PLANE_Y], raw[i].planes[VPX_PLANE_U], raw[i].stride[VPX_PLANE_U], raw[i].planes[VPX_PLANE_V], raw[i].stride[VPX_PLANE_V], raw[i].d_w, raw[i].d_h, 1); } } /* Encode each frame at multi-levels */ if(vpx_codec_encode(&codec[0], frame_avail? &raw[0] : NULL, frame_cnt, 1, flags, arg_deadline)) die_codec(&codec[0], "Failed to encode frame"); for (i=NUM_ENCODERS-1; i>=0 ; i--) { got_data = 0; while( (pkt[i] = vpx_codec_get_cx_data(&codec[i], &iter[i])) ) { got_data = 1; switch(pkt[i]->kind) { case VPX_CODEC_CX_FRAME_PKT: write_ivf_frame_header(outfile[i], pkt[i]); (void) fwrite(pkt[i]->data.frame.buf, 1, pkt[i]->data.frame.sz, outfile[i]); break; case VPX_CODEC_PSNR_PKT: if (show_psnr) { int j; psnr_sse_total[i] += pkt[i]->data.psnr.sse[0]; psnr_samples_total[i] += pkt[i]->data.psnr.samples[0]; for (j = 0; j < 4; j++) { } psnr_count[i]++; } break; default: break; } printf(pkt[i]->kind == VPX_CODEC_CX_FRAME_PKT && (pkt[i]->data.frame.flags & VPX_FRAME_IS_KEY)? "K":"."); fflush(stdout); } } frame_cnt++; } printf("\n"); fclose(infile); printf("Processed %ld frames.\n",(long int)frame_cnt-1); for (i=0; i< NUM_ENCODERS; i++) { /* Calculate PSNR and print it out */ if ( (show_psnr) && (psnr_count[i]>0) ) { int j; double ovpsnr = sse_to_psnr(psnr_samples_total[i], 255.0, psnr_sse_total[i]); fprintf(stderr, "\n ENC%d PSNR (Overall/Avg/Y/U/V)", i); fprintf(stderr, " %.3lf", ovpsnr); for (j = 0; j < 4; j++) { fprintf(stderr, " %.3lf", psnr_totals[i][j]/psnr_count[i]); } } if(vpx_codec_destroy(&codec[i])) die_codec(&codec[i], "Failed to destroy codec"); vpx_img_free(&raw[i]); if(!outfile[i]) continue; /* Try to rewrite the file header with the actual frame count */ if(!fseek(outfile[i], 0, SEEK_SET)) write_ivf_file_header(outfile[i], &cfg[i], frame_cnt-1); fclose(outfile[i]); } printf("\n"); return EXIT_SUCCESS; } 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 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 ssh_throttle_all(Ssh ssh, int enable, int bufsize) { int i; struct ssh_channel *c; if (enable == ssh->throttled_all) return; ssh->throttled_all = enable; ssh->overall_bufsize = bufsize; if (!ssh->channels) return; for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) { switch (c->type) { case CHAN_MAINSESSION: /* * This is treated separately, outside the switch. */ break; x11_override_throttle(c->u.x11.xconn, enable); break; case CHAN_AGENT: /* Agent channels require no buffer management. */ break; case CHAN_SOCKDATA: pfd_override_throttle(c->u.pfd.pf, enable); static void ssh_agent_callback(void *sshv, void *reply, int replylen) { Ssh ssh = (Ssh) sshv; ssh->auth_agent_query = NULL; ssh->agent_response = reply; ssh->agent_response_len = replylen; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_authconn(ssh, NULL, -1, NULL); } static void ssh_dialog_callback(void *sshv, int ret) { Ssh ssh = (Ssh) sshv; ssh->user_response = ret; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_transport(ssh, NULL, -1, NULL); /* * This may have unfrozen the SSH connection, so do a * queued-data run. */ ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) { struct ssh_channel *c = (struct ssh_channel *)cv; const void *sentreply = reply; c->u.a.pending = NULL; c->u.a.outstanding_requests--; if (!sentreply) { /* Fake SSH_AGENT_FAILURE. */ sentreply = "\0\0\0\1\5"; replylen = 5; } ssh_send_channel_data(c, sentreply, replylen); if (reply) sfree(reply); /* * If we've already seen an incoming EOF but haven't sent an * outgoing one, this may be the moment to send it. */ if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF)) sshfwd_write_eof(c); } /* * Client-initiated disconnection. Send a DISCONNECT if `wire_reason' * non-NULL, otherwise just close the connection. `client_reason' == NULL struct Packet *pktin) { int i, j, ret; unsigned char cookie[8], *ptr; struct MD5Context md5c; struct do_ssh1_login_state { int crLine; int len; unsigned char *rsabuf; const unsigned char *keystr1, *keystr2; unsigned long supported_ciphers_mask, supported_auths_mask; int tried_publickey, tried_agent; int tis_auth_refused, ccard_auth_refused; unsigned char session_id[16]; int cipher_type; void *publickey_blob; int publickey_bloblen; char *publickey_comment; int privatekey_available, privatekey_encrypted; prompts_t *cur_prompt; char c; int pwpkt_type; unsigned char request[5], *response, *p; int responselen; int keyi, nkeys; int authed; struct RSAKey key; Bignum challenge; char *commentp; int commentlen; int dlgret; Filename *keyfile; struct RSAKey servkey, hostkey; }; crState(do_ssh1_login_state); crBeginState; if (!pktin) crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_PUBLIC_KEY) { bombout(("Public key packet not received")); crStop(0); } logevent("Received public keys"); ptr = ssh_pkt_getdata(pktin, 8); if (!ptr) { bombout(("SSH-1 public key packet stopped before random cookie")); crStop(0); } memcpy(cookie, ptr, 8); if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) || !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { bombout(("Failed to read SSH-1 public keys from public key packet")); crStop(0); } /* * Log the host key fingerprint. */ { char logmsg[80]; logevent("Host key fingerprint is:"); strcpy(logmsg, " "); s->hostkey.comment = NULL; rsa_fingerprint(logmsg + strlen(logmsg), sizeof(logmsg) - strlen(logmsg), &s->hostkey); logevent(logmsg); } ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin); s->supported_ciphers_mask = ssh_pkt_getuint32(pktin); s->supported_auths_mask = ssh_pkt_getuint32(pktin); if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA); ssh->v1_local_protoflags = ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED; ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER; MD5Init(&md5c); MD5Update(&md5c, s->keystr2, s->hostkey.bytes); MD5Update(&md5c, s->keystr1, s->servkey.bytes); MD5Update(&md5c, cookie, 8); MD5Final(s->session_id, &md5c); for (i = 0; i < 32; i++) ssh->session_key[i] = random_byte(); /* * Verify that the `bits' and `bytes' parameters match. */ if (s->hostkey.bits > s->hostkey.bytes * 8 || s->servkey.bits > s->servkey.bytes * 8) { bombout(("SSH-1 public keys were badly formatted")); crStop(0); } s->len = (s->hostkey.bytes > s->servkey.bytes ? s->hostkey.bytes : s->servkey.bytes); s->rsabuf = snewn(s->len, unsigned char); /* * Verify the host key. */ { /* * First format the key into a string. */ int len = rsastr_len(&s->hostkey); char fingerprint[100]; char *keystr = snewn(len, char); rsastr_fmt(keystr, &s->hostkey); rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey); /* First check against manually configured host keys. */ s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL); if (s->dlgret == 0) { /* did not match */ bombout(("Host key did not appear in manually configured list")); sfree(keystr); crStop(0); } else if (s->dlgret < 0) { /* none configured; use standard handling */ ssh_set_frozen(ssh, 1); s->dlgret = verify_ssh_host_key(ssh->frontend, ssh->savedhost, ssh->savedport, "rsa", keystr, fingerprint, ssh_dialog_callback, ssh); sfree(keystr); #ifdef FUZZING s->dlgret = 1; #endif if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user host key response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at host key verification", NULL, 0, TRUE); crStop(0); } } else { sfree(keystr); } } for (i = 0; i < 32; i++) { s->rsabuf[i] = ssh->session_key[i]; if (i < 16) s->rsabuf[i] ^= s->session_id[i]; } if (s->hostkey.bytes > s->servkey.bytes) { ret = rsaencrypt(s->rsabuf, 32, &s->servkey); if (ret) ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey); } else { ret = rsaencrypt(s->rsabuf, 32, &s->hostkey); if (ret) ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey); } if (!ret) { bombout(("SSH-1 public key encryptions failed due to bad formatting")); crStop(0); } logevent("Encrypted session key"); { int cipher_chosen = 0, warn = 0; const char *cipher_string = NULL; int i; for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) { int next_cipher = conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i); if (next_cipher == CIPHER_WARN) { /* If/when we choose a cipher, warn about it */ warn = 1; } else if (next_cipher == CIPHER_AES) { /* XXX Probably don't need to mention this. */ logevent("AES not supported in SSH-1, skipping"); } else { switch (next_cipher) { case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES; cipher_string = "3DES"; break; case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH; cipher_string = "Blowfish"; break; case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES; cipher_string = "single-DES"; break; } if (s->supported_ciphers_mask & (1 << s->cipher_type)) cipher_chosen = 1; } } if (!cipher_chosen) { if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0) bombout(("Server violates SSH-1 protocol by not " "supporting 3DES encryption")); else /* shouldn't happen */ bombout(("No supported ciphers found")); crStop(0); } /* Warn about chosen cipher if necessary. */ if (warn) { ssh_set_frozen(ssh, 1); s->dlgret = askalg(ssh->frontend, "cipher", cipher_string, ssh_dialog_callback, ssh); if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at cipher warning", NULL, 0, TRUE); crStop(0); } } } switch (s->cipher_type) { case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break; case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break; case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break; } send_packet(ssh, SSH1_CMSG_SESSION_KEY, PKT_CHAR, s->cipher_type, PKT_DATA, cookie, 8, PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF, PKT_DATA, s->rsabuf, s->len, PKT_INT, ssh->v1_local_protoflags, PKT_END); logevent("Trying to enable encryption..."); sfree(s->rsabuf); ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 : s->cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des); ssh->v1_cipher_ctx = ssh->cipher->make_context(); ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key); logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name); ssh->crcda_ctx = crcda_make_context(); logevent("Installing CRC compensation attack detector"); if (s->servkey.modulus) { sfree(s->servkey.modulus); s->servkey.modulus = NULL; } if (s->servkey.exponent) { sfree(s->servkey.exponent); s->servkey.exponent = NULL; } if (s->hostkey.modulus) { sfree(s->hostkey.modulus); s->hostkey.modulus = NULL; } if (s->hostkey.exponent) { sfree(s->hostkey.exponent); s->hostkey.exponent = NULL; } crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Encryption not successfully enabled")); crStop(0); } logevent("Successfully started encryption"); fflush(stdout); /* FIXME eh? */ { if ((ssh->username = get_remote_username(ssh->conf)) == NULL) { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH login name"); add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a username. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE); crStop(0); } ssh->username = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END); { char *userlog = dupprintf("Sent username \"%s\"", ssh->username); logevent(userlog); if (flags & FLAG_INTERACTIVE && (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) { c_write_str(ssh, userlog); c_write_str(ssh, "\r\n"); } sfree(userlog); } } crWaitUntil(pktin); if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) { /* We must not attempt PK auth. Pretend we've already tried it. */ s->tried_publickey = s->tried_agent = 1; } else { s->tried_publickey = s->tried_agent = 0; } s->tis_auth_refused = s->ccard_auth_refused = 0; /* * Load the public half of any configured keyfile for later use. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); if (!filename_is_null(s->keyfile)) { int keytype; logeventf(ssh, "Reading key file \"%.150s\"", filename_to_str(s->keyfile)); keytype = key_type(s->keyfile); if (keytype == SSH_KEYTYPE_SSH1 || keytype == SSH_KEYTYPE_SSH1_PUBLIC) { const char *error; if (rsakey_pubblob(s->keyfile, &s->publickey_blob, &s->publickey_bloblen, &s->publickey_comment, &error)) { s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1); if (!s->privatekey_available) logeventf(ssh, "Key file contains public key only"); s->privatekey_encrypted = rsakey_encrypted(s->keyfile, NULL); } else { char *msgbuf; logeventf(ssh, "Unable to load key (%s)", error); msgbuf = dupprintf("Unable to load key file " "\"%.150s\" (%s)\r\n", filename_to_str(s->keyfile), error); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else { char *msgbuf; logeventf(ssh, "Unable to use this key file (%s)", key_type_to_str(keytype)); msgbuf = dupprintf("Unable to use key file \"%.150s\"" " (%s)\r\n", filename_to_str(s->keyfile), key_type_to_str(keytype)); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else s->publickey_blob = NULL; while (pktin->type == SSH1_SMSG_FAILURE) { s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD; if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) { /* * Attempt RSA authentication using Pageant. */ void *r; s->authed = FALSE; s->tried_agent = 1; logevent("Pageant is running. Requesting keys."); /* Request the keys held by the agent. */ PUT_32BIT(s->request, 1); s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES; ssh->auth_agent_query = agent_query( s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for agent response")); crStop(0); } } while (pktin || inlen > 0); r = ssh->agent_response; s->responselen = ssh->agent_response_len; } s->response = (unsigned char *) r; if (s->response && s->responselen >= 5 && s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) { s->p = s->response + 5; s->nkeys = toint(GET_32BIT(s->p)); if (s->nkeys < 0) { logeventf(ssh, "Pageant reported negative key count %d", s->nkeys); s->nkeys = 0; } s->p += 4; logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys); for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) { unsigned char *pkblob = s->p; s->p += 4; { int n, ok = FALSE; do { /* do while (0) to make breaking easy */ n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.exponent); if (n < 0) break; s->p += n; n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.modulus); if (n < 0) break; s->p += n; if (s->responselen - (s->p-s->response) < 4) break; s->commentlen = toint(GET_32BIT(s->p)); s->p += 4; if (s->commentlen < 0 || toint(s->responselen - (s->p-s->response)) < s->commentlen) break; s->commentp = (char *)s->p; s->p += s->commentlen; ok = TRUE; } while (0); if (!ok) { logevent("Pageant key list packet was truncated"); break; } } if (s->publickey_blob) { if (!memcmp(pkblob, s->publickey_blob, s->publickey_bloblen)) { logeventf(ssh, "Pageant key #%d matches " "configured key file", s->keyi); s->tried_publickey = 1; } else /* Skip non-configured key */ continue; } logeventf(ssh, "Trying Pageant key #%d", s->keyi); send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { logevent("Key refused"); continue; } logevent("Received RSA challenge"); if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } { char *agentreq, *q, *ret; void *vret; int len, retlen; len = 1 + 4; /* message type, bit count */ len += ssh1_bignum_length(s->key.exponent); len += ssh1_bignum_length(s->key.modulus); len += ssh1_bignum_length(s->challenge); len += 16; /* session id */ len += 4; /* response format */ agentreq = snewn(4 + len, char); PUT_32BIT(agentreq, len); q = agentreq + 4; *q++ = SSH1_AGENTC_RSA_CHALLENGE; PUT_32BIT(q, bignum_bitcount(s->key.modulus)); q += 4; q += ssh1_write_bignum(q, s->key.exponent); q += ssh1_write_bignum(q, s->key.modulus); q += ssh1_write_bignum(q, s->challenge); memcpy(q, s->session_id, 16); q += 16; PUT_32BIT(q, 1); /* response format */ ssh->auth_agent_query = agent_query( agentreq, len + 4, &vret, &retlen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { sfree(agentreq); do { crReturn(0); if (pktin) { bombout(("Unexpected data from server" " while waiting for agent" " response")); crStop(0); } } while (pktin || inlen > 0); vret = ssh->agent_response; retlen = ssh->agent_response_len; } else sfree(agentreq); ret = vret; if (ret) { if (ret[4] == SSH1_AGENT_RSA_RESPONSE) { logevent("Sending Pageant's response"); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, ret + 5, 16, PKT_END); sfree(ret); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_SUCCESS) { logevent ("Pageant's response accepted"); if (flags & FLAG_VERBOSE) { c_write_str(ssh, "Authenticated using" " RSA key \""); c_write(ssh, s->commentp, s->commentlen); c_write_str(ssh, "\" from agent\r\n"); } s->authed = TRUE; } else logevent ("Pageant's response not accepted"); } else { logevent ("Pageant failed to answer challenge"); sfree(ret); } } else { logevent("No reply received from Pageant"); } } freebn(s->key.exponent); freebn(s->key.modulus); freebn(s->challenge); if (s->authed) break; } sfree(s->response); if (s->publickey_blob && !s->tried_publickey) logevent("Configured key file not in Pageant"); } else { logevent("Failed to get reply from Pageant"); } if (s->authed) break; } if (s->publickey_blob && s->privatekey_available && !s->tried_publickey) { /* * Try public key authentication with the specified * key file. */ int got_passphrase; /* need not be kept over crReturn */ if (flags & FLAG_VERBOSE) c_write_str(ssh, "Trying public key authentication.\r\n"); s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); logeventf(ssh, "Trying public key \"%s\"", filename_to_str(s->keyfile)); s->tried_publickey = 1; got_passphrase = FALSE; while (!got_passphrase) { /* * Get a passphrase, if necessary. */ char *passphrase = NULL; /* only written after crReturn */ const char *error; if (!s->privatekey_encrypted) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "No passphrase required.\r\n"); passphrase = NULL; } else { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = FALSE; s->cur_prompt->name = dupstr("SSH key passphrase"); add_prompt(s->cur_prompt, dupprintf("Passphrase for key \"%.100s\": ", s->publickey_comment), FALSE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* Failed to get a passphrase. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } passphrase = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } /* * Try decrypting key with passphrase. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); ret = loadrsakey(s->keyfile, &s->key, passphrase, &error); if (passphrase) { smemclr(passphrase, strlen(passphrase)); sfree(passphrase); } if (ret == 1) { /* Correct passphrase. */ got_passphrase = TRUE; } else if (ret == 0) { c_write_str(ssh, "Couldn't load private key from "); c_write_str(ssh, filename_to_str(s->keyfile)); c_write_str(ssh, " ("); c_write_str(ssh, error); c_write_str(ssh, ").\r\n"); got_passphrase = FALSE; break; /* go and try something else */ } else if (ret == -1) { c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */ got_passphrase = FALSE; /* and try again */ } else { assert(0 && "unexpected return from loadrsakey()"); got_passphrase = FALSE; /* placate optimisers */ } } if (got_passphrase) { /* * Send a public key attempt. */ send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { c_write_str(ssh, "Server refused our public key.\r\n"); continue; /* go and try something else */ } if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { bombout(("Bizarre response to offer of public key")); crStop(0); } { int i; unsigned char buffer[32]; Bignum challenge, response; if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } response = rsadecrypt(challenge, &s->key); freebn(s->key.private_exponent);/* burn the evidence */ for (i = 0; i < 32; i++) { buffer[i] = bignum_byte(response, 31 - i); } MD5Init(&md5c); MD5Update(&md5c, buffer, 32); MD5Update(&md5c, s->session_id, 16); MD5Final(buffer, &md5c); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, buffer, 16, PKT_END); freebn(challenge); freebn(response); } crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Failed to authenticate with" " our public key.\r\n"); continue; /* go and try something else */ } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Bizarre response to RSA authentication response")); crStop(0); } break; /* we're through! */ } } /* * Otherwise, try various forms of password-like authentication. */ s->cur_prompt = new_prompts(ssh->frontend); if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) && !s->tis_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE; logevent("Requested TIS authentication"); send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) { logevent("TIS authentication declined"); if (flags & FLAG_INTERACTIVE) c_write_str(ssh, "TIS authentication refused.\r\n"); s->tis_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("TIS challenge packet was badly formed")); crStop(0); } logevent("Received TIS challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH TIS authentication"); /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using TIS authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) && !s->ccard_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE; logevent("Requested CryptoCard authentication"); send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) { logevent("CryptoCard authentication declined"); c_write_str(ssh, "CryptoCard authentication refused.\r\n"); s->ccard_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("CryptoCard challenge packet was badly formed")); crStop(0); } logevent("Received CryptoCard challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH CryptoCard authentication"); s->cur_prompt->name_reqd = FALSE; /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using CryptoCard authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) { bombout(("No supported authentication methods available")); crStop(0); } s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH password"); add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ", ssh->username, ssh->savedhost), FALSE); } /* * Show password prompt, having first obtained it via a TIS * or CryptoCard exchange if we're doing TIS or CryptoCard * authentication. */ { int ret; /* need not be kept over crReturn */ ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a password (for example * because one was supplied on the command line * which has already failed to work). Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { /* * Defence against traffic analysis: we send a * whole bunch of packets containing strings of * different lengths. One of these strings is the * password, in a SSH1_CMSG_AUTH_PASSWORD packet. * The others are all random data in * SSH1_MSG_IGNORE packets. This way a passive * listener can't tell which is the password, and * hence can't deduce the password length. * * Anybody with a password length greater than 16 * bytes is going to have enough entropy in their * password that a listener won't find it _that_ * much help to know how long it is. So what we'll * do is: * * - if password length < 16, we send 15 packets * containing string lengths 1 through 15 * * - otherwise, we let N be the nearest multiple * of 8 below the password length, and send 8 * packets containing string lengths N through * N+7. This won't obscure the order of * magnitude of the password length, but it will * introduce a bit of extra uncertainty. * * A few servers can't deal with SSH1_MSG_IGNORE, at * least in this context. For these servers, we need * an alternative defence. We make use of the fact * that the password is interpreted as a C string: * so we can append a NUL, then some random data. * * A few servers can deal with neither SSH1_MSG_IGNORE * here _nor_ a padded password string. * For these servers we are left with no defences * against password length sniffing. */ if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) && !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can deal with SSH1_MSG_IGNORE, so * we can use the primary defence. */ int bottom, top, pwlen, i; char *randomstr; pwlen = strlen(s->cur_prompt->prompts[0]->result); if (pwlen < 16) { bottom = 0; /* zero length passwords are OK! :-) */ top = 15; } else { bottom = pwlen & ~7; top = bottom + 7; } assert(pwlen >= bottom && pwlen <= top); randomstr = snewn(top + 1, char); for (i = bottom; i <= top; i++) { if (i == pwlen) { defer_packet(ssh, s->pwpkt_type, PKT_STR,s->cur_prompt->prompts[0]->result, PKT_END); } else { for (j = 0; j < i; j++) { do { randomstr[j] = random_byte(); } while (randomstr[j] == '\0'); } randomstr[i] = '\0'; defer_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, randomstr, PKT_END); } } logevent("Sending password with camouflage packets"); ssh_pkt_defersend(ssh); sfree(randomstr); } else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can't deal with SSH1_MSG_IGNORE * but can deal with padded passwords, so we * can use the secondary defence. */ char string[64]; char *ss; int len; len = strlen(s->cur_prompt->prompts[0]->result); if (len < sizeof(string)) { ss = string; strcpy(string, s->cur_prompt->prompts[0]->result); len++; /* cover the zero byte */ while (len < sizeof(string)) { string[len++] = (char) random_byte(); } } else { ss = s->cur_prompt->prompts[0]->result; } logevent("Sending length-padded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, ss, len, PKT_END); } else { /* * The server is believed unable to cope with * any of our password camouflage methods. */ int len; len = strlen(s->cur_prompt->prompts[0]->result); logevent("Sending unpadded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, s->cur_prompt->prompts[0]->result, len, PKT_END); } } else { send_packet(ssh, s->pwpkt_type, PKT_STR, s->cur_prompt->prompts[0]->result, PKT_END); } logevent("Sent password"); free_prompts(s->cur_prompt); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Access denied\r\n"); logevent("Authentication refused"); } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Strange packet received, type %d", pktin->type)); crStop(0); } } /* Clear up */ if (s->publickey_blob) { sfree(s->publickey_blob); sfree(s->publickey_comment); } logevent("Authentication successful"); crFinish(1); } static void ssh_channel_try_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; assert(c->pending_eof); /* precondition for calling us */ if (c->halfopen) return; /* can't close: not even opened yet */ if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0) return; /* can't send EOF: pending outgoing data */ c->pending_eof = FALSE; /* we're about to send it */ if (ssh->version == 1) { send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END); c->closes |= CLOSES_SENT_EOF; } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF); ssh2_pkt_adduint32(pktout, c->remoteid); ssh2_pkt_send(ssh, pktout); c->closes |= CLOSES_SENT_EOF; ssh2_channel_check_close(c); } } Conf *sshfwd_get_conf(struct ssh_channel *c) { Ssh ssh = c->ssh; return ssh->conf; } void sshfwd_write_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; if (c->closes & CLOSES_SENT_EOF) return; c->pending_eof = TRUE; ssh_channel_try_eof(c); } void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { Ssh ssh = c->ssh; char *reason; if (ssh->state == SSH_STATE_CLOSED) return; reason = dupprintf("due to local error: %s", err); ssh_channel_close_local(c, reason); sfree(reason); c->pending_eof = FALSE; /* this will confuse a zombie channel */ ssh2_channel_check_close(c); } int sshfwd_write(struct ssh_channel *c, char *buf, int len) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return 0; return ssh_send_channel_data(c, buf, len); } void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; ssh_channel_unthrottle(c, bufsize); } static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin) { struct queued_handler *qh = ssh->qhead; assert(qh != NULL); assert(pktin->type == qh->msg1 || pktin->type == qh->msg2); if (qh->msg1 > 0) { assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1; } if (qh->msg2 > 0) { assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2; } if (qh->next) { ssh->qhead = qh->next; if (ssh->qhead->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler; } if (ssh->qhead->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler; } } else { ssh->qhead = ssh->qtail = NULL; } qh->handler(ssh, pktin, qh->ctx); sfree(qh); } static void ssh_queue_handler(Ssh ssh, int msg1, int msg2, chandler_fn_t handler, void *ctx) { struct queued_handler *qh; qh = snew(struct queued_handler); qh->msg1 = msg1; qh->msg2 = msg2; qh->handler = handler; qh->ctx = ctx; qh->next = NULL; if (ssh->qtail == NULL) { ssh->qhead = qh; if (qh->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler; } if (qh->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler; } } else { ssh->qtail->next = qh; } ssh->qtail = qh; } static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx) { struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx; if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS : SSH2_MSG_REQUEST_SUCCESS)) { logeventf(ssh, "Remote port forwarding from %s enabled", pf->sportdesc); } else { logeventf(ssh, "Remote port forwarding from %s refused", pf->sportdesc); rpf = del234(ssh->rportfwds, pf); assert(rpf == pf); pf->pfrec->remote = NULL; free_rportfwd(pf); } } int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport, void *share_ctx) { struct ssh_rportfwd *pf = snew(struct ssh_rportfwd); pf->dhost = NULL; pf->dport = 0; pf->share_ctx = share_ctx; pf->shost = dupstr(shost); pf->sport = sport; pf->sportdesc = NULL; if (!ssh->rportfwds) { assert(ssh->version == 2); ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } if (add234(ssh->rportfwds, pf) != pf) { sfree(pf->shost); sfree(pf); return FALSE; } return TRUE; } static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin, void *ctx) { share_got_pkt_from_server(ctx, pktin->type, pktin->body, pktin->length); } void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx) { ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_sharing_global_request_response, share_ctx); } static void ssh_setup_portfwd(Ssh ssh, Conf *conf) { struct ssh_portfwd *epf; int i; char *key, *val; if (!ssh->portfwds) { ssh->portfwds = newtree234(ssh_portcmp); } else { /* * Go through the existing port forwardings and tag them * with status==DESTROY. Any that we want to keep will be * re-enabled (status==KEEP) as we go through the * configuration and find out which bits are the same as * they were before. */ struct ssh_portfwd *epf; int i; for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) epf->status = DESTROY; } for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key); val != NULL; val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) { char *kp, *kp2, *vp, *vp2; char address_family, type; int sport,dport,sserv,dserv; char *sports, *dports, *saddr, *host; kp = key; address_family = 'A'; type = 'L'; if (*kp == 'A' || *kp == '4' || *kp == '6') address_family = *kp++; if (*kp == 'L' || *kp == 'R') type = *kp++; if ((kp2 = host_strchr(kp, ':')) != NULL) { /* * There's a colon in the middle of the source port * string, which means that the part before it is * actually a source address. */ char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp); saddr = host_strduptrim(saddr_tmp); sfree(saddr_tmp); sports = kp2+1; } else { saddr = NULL; sports = kp; } sport = atoi(sports); sserv = 0; if (sport == 0) { sserv = 1; sport = net_service_lookup(sports); if (!sport) { logeventf(ssh, "Service lookup failed for source" " port \"%s\"", sports); } } if (type == 'L' && !strcmp(val, "D")) { /* dynamic forwarding */ host = NULL; dports = NULL; dport = -1; dserv = 0; type = 'D'; } else { /* ordinary forwarding */ vp = val; vp2 = vp + host_strcspn(vp, ":"); host = dupprintf("%.*s", (int)(vp2 - vp), vp); if (*vp2) vp2++; dports = vp2; dport = atoi(dports); dserv = 0; if (dport == 0) { dserv = 1; dport = net_service_lookup(dports); if (!dport) { logeventf(ssh, "Service lookup failed for destination" " port \"%s\"", dports); } } } if (sport && dport) { /* Set up a description of the source port. */ struct ssh_portfwd *pfrec, *epfrec; pfrec = snew(struct ssh_portfwd); pfrec->type = type; pfrec->saddr = saddr; pfrec->sserv = sserv ? dupstr(sports) : NULL; pfrec->sport = sport; pfrec->daddr = host; pfrec->dserv = dserv ? dupstr(dports) : NULL; pfrec->dport = dport; pfrec->local = NULL; pfrec->remote = NULL; pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 : address_family == '6' ? ADDRTYPE_IPV6 : ADDRTYPE_UNSPEC); epfrec = add234(ssh->portfwds, pfrec); if (epfrec != pfrec) { if (epfrec->status == DESTROY) { /* * We already have a port forwarding up and running * with precisely these parameters. Hence, no need * to do anything; simply re-tag the existing one * as KEEP. */ epfrec->status = KEEP; } /* * Anything else indicates that there was a duplicate * in our input, which we'll silently ignore. */ free_portfwd(pfrec); } else { pfrec->status = CREATE; } } else { sfree(saddr); sfree(host); } } /* * Now go through and destroy any port forwardings which were * not re-enabled. */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == DESTROY) { char *message; message = dupprintf("%s port forwarding from %s%s%d", epf->type == 'L' ? "local" : epf->type == 'R' ? "remote" : "dynamic", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sport); if (epf->type != 'D') { char *msg2 = dupprintf("%s to %s:%d", message, epf->daddr, epf->dport); sfree(message); message = msg2; } logeventf(ssh, "Cancelling %s", message); sfree(message); /* epf->remote or epf->local may be NULL if setting up a * forwarding failed. */ if (epf->remote) { struct ssh_rportfwd *rpf = epf->remote; struct Packet *pktout; /* * Cancel the port forwarding at the server * end. */ if (ssh->version == 1) { /* * We cannot cancel listening ports on the * server side in SSH-1! There's no message * to support it. Instead, we simply remove * the rportfwd record from the local end * so that any connections the server tries * to make on it are rejected. */ } else { pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "cancel-tcpip-forward"); ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */ if (epf->saddr) { ssh2_pkt_addstring(pktout, epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { /* XXX: rport_acceptall may not represent * what was used to open the original connection, * since it's reconfigurable. */ ssh2_pkt_addstring(pktout, ""); } else { ssh2_pkt_addstring(pktout, "localhost"); } ssh2_pkt_adduint32(pktout, epf->sport); ssh2_pkt_send(ssh, pktout); } del234(ssh->rportfwds, rpf); free_rportfwd(rpf); } else if (epf->local) { pfl_terminate(epf->local); } delpos234(ssh->portfwds, i); free_portfwd(epf); i--; /* so we don't skip one in the list */ } /* * And finally, set up any new port forwardings (status==CREATE). */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == CREATE) { char *sportdesc, *dportdesc; sportdesc = dupprintf("%s%s%s%s%d%s", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sserv ? epf->sserv : "", epf->sserv ? "(" : "", epf->sport, epf->sserv ? ")" : ""); if (epf->type == 'D') { dportdesc = NULL; } else { dportdesc = dupprintf("%s:%s%s%d%s", epf->daddr, epf->dserv ? epf->dserv : "", epf->dserv ? "(" : "", epf->dport, epf->dserv ? ")" : ""); } if (epf->type == 'L') { char *err = pfl_listen(epf->daddr, epf->dport, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s forwarding to %s%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, dportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else if (epf->type == 'D') { char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else { struct ssh_rportfwd *pf; /* * Ensure the remote port forwardings tree exists. */ if (!ssh->rportfwds) { if (ssh->version == 1) ssh->rportfwds = newtree234(ssh_rportcmp_ssh1); else ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } pf = snew(struct ssh_rportfwd); pf->share_ctx = NULL; pf->dhost = dupstr(epf->daddr); pf->dport = epf->dport; if (epf->saddr) { pf->shost = dupstr(epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { pf->shost = dupstr(""); } else { pf->shost = dupstr("localhost"); } pf->sport = epf->sport; if (add234(ssh->rportfwds, pf) != pf) { logeventf(ssh, "Duplicate remote port forwarding to %s:%d", epf->daddr, epf->dport); sfree(pf); } else { logeventf(ssh, "Requesting remote port %s" " forward to %s", sportdesc, dportdesc); pf->sportdesc = sportdesc; sportdesc = NULL; epf->remote = pf; pf->pfrec = epf; if (ssh->version == 1) { send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST, PKT_INT, epf->sport, PKT_STR, epf->daddr, PKT_INT, epf->dport, PKT_END); ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS, SSH1_SMSG_FAILURE, ssh_rportfwd_succfail, pf); } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "tcpip-forward"); ssh2_pkt_addbool(pktout, 1);/* want reply */ ssh2_pkt_addstring(pktout, pf->shost); ssh2_pkt_adduint32(pktout, pf->sport); ssh2_pkt_send(ssh, pktout); ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_rportfwd_succfail, pf); } } } sfree(sportdesc); sfree(dportdesc); } } static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin) { char *string; int stringlen, bufsize; ssh_pkt_getstring(pktin, &string, &stringlen); if (string == NULL) { bombout(("Incoming terminal data packet was badly formed")); return; } bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA, string, stringlen); if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) { ssh->v1_stdout_throttling = 1; ssh_throttle_conn(ssh, +1); } } static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * X-Server. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); logevent("Received X11 connect request"); /* Refuse if X11 forwarding is disabled. */ if (!ssh->X11_fwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); logevent("Rejected X11 connect request"); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_X11; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Opened X11 forward channel"); } } static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * agent. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); /* Refuse if agent forwarding is disabled. */ if (!ssh->agentfwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.lensofar = 0; c->u.a.message = NULL; c->u.a.pending = NULL; c->u.a.outstanding_requests = 0; send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); } } static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to a * forwarded port. Give them back a local channel number. */ struct ssh_rportfwd pf, *pfp; int remoteid; int hostsize, port; char *host; char *err; remoteid = ssh_pkt_getuint32(pktin); ssh_pkt_getstring(pktin, &host, &hostsize); port = ssh_pkt_getuint32(pktin); pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host)); pf.dport = port; pfp = find234(ssh->rportfwds, &pf, NULL); if (pfp == NULL) { logeventf(ssh, "Rejected remote port open request for %s:%d", pf.dhost, port); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { struct ssh_channel *c = snew(struct ssh_channel); c->ssh = ssh; logeventf(ssh, "Received remote port open request for %s:%d", pf.dhost, port); err = pfd_connect(&c->u.pfd.pf, pf.dhost, port, c, ssh->conf, pfp->pfrec->addressfamily); if (err != NULL) { logeventf(ssh, "Port open failed: %s", err); sfree(err); sfree(c); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_SOCKDATA; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Forwarded port opened successfully"); } } sfree(pf.dhost); } static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin) { struct ssh_channel *c; c = ssh_channel_msg(ssh, pktin); if (c && c->type == CHAN_SOCKDATA) { c->remoteid = ssh_pkt_getuint32(pktin); c->halfopen = FALSE; c->throttling_conn = 0; pfd_confirm(c->u.pfd.pf); } if (c && c->pending_eof) { /* * We have a pending close on this channel, * which we decided on before the server acked * the channel open. So now we know the * remoteid, we can close it again. */ ssh_channel_try_eof(c); } } c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.lensofar = 0; c->u.a.message = NULL; c->u.a.pending = NULL; c->u.a.outstanding_requests = 0; send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); del234(ssh->channels, c); sfree(c); } } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static void backref_insert(struct rb_root *root, struct sa_defrag_extent_backref *backref) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct sa_defrag_extent_backref *entry; int ret; while (*p) { parent = *p; entry = rb_entry(parent, struct sa_defrag_extent_backref, node); ret = backref_comp(backref, entry); if (ret < 0) p = &(*p)->rb_left; else p = &(*p)->rb_right; } rb_link_node(&backref->node, parent, p); rb_insert_color(&backref->node, root); } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[email protected]> 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: DefragVlanTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358 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: TestNativeHandler::TestNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetWakeEventPage", base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 Target: 1 Example 2: Code: static int tracing_wait_pipe(struct file *filp) { struct trace_iterator *iter = filp->private_data; int ret; while (trace_empty(iter)) { if ((filp->f_flags & O_NONBLOCK)) { return -EAGAIN; } /* * We block until we read something and tracing is disabled. * We still block if tracing is disabled, but we have never * read anything. This allows a user to cat this file, and * then enable tracing. But after we have read something, * we give an EOF when tracing is again disabled. * * iter->pos will be 0 if we haven't read anything. */ if (!tracer_tracing_is_on(iter->tr) && iter->pos) break; mutex_unlock(&iter->mutex); ret = wait_on_pipe(iter, false); mutex_lock(&iter->mutex); if (ret) return ret; } return 1; } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 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 HistogramsCallback() { MockHistogramsCallback(); QuitMessageLoop(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94 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 BluetoothDeviceChromeOS::DisplayPinCode( const dbus::ObjectPath& device_path, const std::string& pincode) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": DisplayPinCode: " << pincode; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_DISPLAY_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); pairing_delegate_->DisplayPinCode(this, pincode); pairing_delegate_used_ = true; } 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 ResetPredictor(bool small_db = true) { if (loading_predictor_) loading_predictor_->Shutdown(); LoadingPredictorConfig config; PopulateTestConfig(&config, small_db); loading_predictor_ = std::make_unique<LoadingPredictor>(config, profile_.get()); predictor_ = loading_predictor_->resource_prefetch_predictor(); predictor_->set_mock_tables(mock_tables_); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} 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: static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } 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:
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 Resource::LastPluginRefWasDeleted(bool instance_destroyed) { DCHECK(resource_id_ != 0); instance()->module()->GetCallbackTracker()->PostAbortForResource( resource_id_); resource_id_ = 0; if (instance_destroyed) instance_ = NULL; } 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: void GLES2DecoderPassthroughImpl::MarkContextLost( error::ContextLostReason reason) { if (WasContextLost()) { return; } command_buffer_service()->SetContextLostReason(reason); context_lost_ = 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: int pnm_validate(jas_stream_t *in) { uchar buf[2]; int i; int n; assert(JAS_STREAM_MAXPUTBACK >= 2); /* Read the first two characters that constitute the signature. */ if ((n = jas_stream_read(in, buf, 2)) < 0) { return -1; } /* Put these characters back to the stream. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough data? */ if (n < 2) { return -1; } /* Is this the correct signature for a PNM file? */ if (buf[0] == 'P' && isdigit(buf[1])) { return 0; } return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. 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: do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk; struct mm_struct *mm; int fault, sig, code; if (notify_page_fault(regs, fsr)) return 0; tsk = current; mm = tsk->mm; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto no_context; /* * As per x86, we may deadlock here. However, since the kernel only * validly references user space from well defined areas of the code, * we can bug out early if this is from code which shouldn't. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; 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(); #ifdef CONFIG_DEBUG_VM if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; #endif } fault = __do_page_fault(mm, addr, fsr, tsk); up_read(&mm->mmap_sem); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, addr); if (fault & VM_FAULT_MAJOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, addr); else if (fault & VM_FAULT_MINOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, addr); /* * Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) return 0; if (fault & VM_FAULT_OOM) { /* * We ran out of memory, call the OOM killer, and return to * userspace (which will retry the fault, or kill us if we * got oom-killed) */ pagefault_out_of_memory(); return 0; } /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ if (!user_mode(regs)) goto no_context; if (fault & VM_FAULT_SIGBUS) { /* * We had some memory, but were unable to * successfully fix up this page fault. */ sig = SIGBUS; code = BUS_ADRERR; } else { /* * Something tried to access memory that * isn't in our memory map.. */ sig = SIGSEGV; code = fault == VM_FAULT_BADACCESS ? SEGV_ACCERR : SEGV_MAPERR; } __do_user_fault(tsk, addr, fsr, sig, code, regs); return 0; no_context: __do_kernel_fault(mm, addr, fsr, regs); return 0; } 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 Target: 1 Example 2: Code: int udpv6_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return ipv6_getsockopt(sk, level, optname, optval, optlen); } Commit Message: ipv6: udp: fix the wrong headroom check At this point, skb->data points to skb_transport_header. So, headroom check is wrong. For some case:bridge(UFO is on) + eth device(UFO is off), there is no enough headroom for IPv6 frag head. But headroom check is always false. This will bring about data be moved to there prior to skb->head, when adding IPv6 frag header to skb. Signed-off-by: Shan Wei <[email protected]> Acked-by: Herbert Xu <[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: void WriteFromUrlOperation::Download(const base::Closure& continuation) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { return; } download_continuation_ = continuation; SetStage(image_writer_api::STAGE_DOWNLOAD); url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); url_fetcher_->Start(); } Commit Message: Network traffic annotation added to extensions::image_writer::WriteFromUrlOperation. Network traffic annotation is added to network request of extensions::image_writer::WriteFromUrlOperation. BUG=656607 Review-Url: https://codereview.chromium.org/2691963002 Cr-Commit-Position: refs/heads/master@{#451456} 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 RenderFlexibleBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBlock::styleDidChange(diff, oldStyle); if (oldStyle && oldStyle->alignItems() == ItemPositionStretch && diff == StyleDifferenceLayout) { for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) { ItemPosition previousAlignment = resolveAlignment(oldStyle, child->style()); if (previousAlignment == ItemPositionStretch && previousAlignment != resolveAlignment(style(), child->style())) child->setChildNeedsLayout(MarkOnlyThis); } } } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static void list_slab_objects(struct kmem_cache *s, struct page *page, const char *text) { #ifdef CONFIG_SLUB_DEBUG void *addr = page_address(page); void *p; DECLARE_BITMAP(map, page->objects); bitmap_zero(map, page->objects); slab_err(s, page, "%s", text); slab_lock(page); for_each_free_object(p, s, page->freelist) set_bit(slab_index(p, s, addr), map); for_each_object(p, s, addr, page->objects) { if (!test_bit(slab_index(p, s, addr), map)) { printk(KERN_ERR "INFO: Object 0x%p @offset=%tu\n", p, p - addr); print_tracking(s, p); } } slab_unlock(page); #endif } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: static int ape_read_close(AVFormatContext * s) { APEContext *ape = s->priv_data; av_freep(&ape->frames); av_freep(&ape->seektable); return 0; } Commit Message: Do not attempt to decode APE file with no frames This fixes invalid reads/writes with this sample: http://packetstorm.linuxsecurity.com/1103-exploits/vlc105-dos.txt 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 LoginHtmlDialog::GetDialogSize(gfx::Size* size) const { size->SetSize(width_, height_); } Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: virtual status_t removeKeys(Vector<uint8_t> const &keySetId) { Parcel data, reply; data.writeInterfaceToken(IDrm::getInterfaceDescriptor()); writeVector(data, keySetId); status_t status = remote()->transact(REMOVE_KEYS, data, &reply); if (status != OK) { return status; } 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: static void reds_stream_push_channel_event(RedsStream *s, int event) { main_dispatcher_channel_event(event, s->info); } Commit Message: 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 get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } Commit Message: avcodec/jpeg2000dec: non zero image offsets are not supported Fixes out of array accesses Fixes Ticket3080 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: int regulator_sync_voltage(struct regulator *regulator) { struct regulator_dev *rdev = regulator->rdev; int ret, min_uV, max_uV; mutex_lock(&rdev->mutex); if (!rdev->desc->ops->set_voltage && !rdev->desc->ops->set_voltage_sel) { ret = -EINVAL; goto out; } /* This is only going to work if we've had a voltage configured. */ if (!regulator->min_uV && !regulator->max_uV) { ret = -EINVAL; goto out; } min_uV = regulator->min_uV; max_uV = regulator->max_uV; /* This should be a paranoia check... */ ret = regulator_check_voltage(rdev, &min_uV, &max_uV); if (ret < 0) goto out; ret = regulator_check_consumers(rdev, &min_uV, &max_uV); if (ret < 0) goto out; ret = _regulator_do_set_voltage(rdev, min_uV, max_uV); out: mutex_unlock(&rdev->mutex); return ret; } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[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 void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int 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 void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } } 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 Target: 1 Example 2: Code: void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType() { bool captionsVisible = mediaElement().textTracksVisible(); setDisplayType(captionsVisible ? MediaHideClosedCaptionsButton : MediaShowClosedCaptionsButton); } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} 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 struct acm *acm_get_by_minor(unsigned int minor) { struct acm *acm; mutex_lock(&acm_minors_lock); acm = idr_find(&acm_minors, minor); if (acm) { mutex_lock(&acm->mutex); if (acm->disconnected) { mutex_unlock(&acm->mutex); acm = NULL; } else { tty_port_get(&acm->port); mutex_unlock(&acm->mutex); } } mutex_unlock(&acm_minors_lock); return acm; } Commit Message: USB: cdc-acm: more sanity checking An attack has become available which pretends to be a quirky device circumventing normal sanity checks and crashes the kernel by an insufficient number of interfaces. This patch adds a check to the code path for quirky devices. Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Greg Kroah-Hartman <[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 ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd) { struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv; u8 b[] = { 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; memcpy(&b[4], cmd->msg, cmd->msg_len); state->config->send_command(fe, 0x72, sizeof(b) - (6 - cmd->msg_len), b, NULL, NULL); return 0; } Commit Message: [media] ttusb-dec: buffer overflow in ioctl We need to add a limit check here so we don't overflow the buffer. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: RTCPeerConnectionHandlerChromium::~RTCPeerConnectionHandlerChromium() { } 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 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 MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck( const KURL& current_src) { DCHECK(IsMainThread()); return Context()->GetSecurityOrigin() && Context()->GetSecurityOrigin()->CanRequest(current_src); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} 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 size_t hash_str(const void *ptr) { const char *str = (const char *)ptr; size_t hash = 5381; size_t c; while((c = (size_t)*str)) { hash = ((hash << 5) + hash) + c; str++; } return hash; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310 Target: 1 Example 2: Code: void OomInterventionTabHelper::OnNearOomDetected() { DCHECK(!OomInterventionConfig::GetInstance()->should_detect_in_renderer()); DCHECK_EQ(web_contents()->GetVisibility(), content::Visibility::VISIBLE); DCHECK(!near_oom_detected_time_); subscription_.reset(); StartDetectionInRenderer(); DCHECK(!renderer_detection_timer_.IsRunning()); renderer_detection_timer_.Start( FROM_HERE, kRendererHighMemoryUsageDetectionWindow, base::BindRepeating(&OomInterventionTabHelper:: OnDetectionWindowElapsedWithoutHighMemoryUsage, weak_ptr_factory_.GetWeakPtr())); } Commit Message: OomIntervention opt-out should work properly with 'show original' OomIntervention should not be re-triggered on the same page if the user declines the intervention once. This CL fixes the bug. Bug: 889131, 887119 Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8 Reviewed-on: https://chromium-review.googlesource.com/1245019 Commit-Queue: Yuzu Saijo <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#594574} 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 int has_dir_name(git_index *index, const git_index_entry *entry, int ok_to_replace) { int retval = 0; int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; const char *slash = name + strlen(name); for (;;) { size_t len, pos; for (;;) { if (*--slash == '/') break; if (slash <= entry->path) return retval; } len = slash - name; if (!index_find(&pos, index, name, len, stage)) { retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, pos) < 0) break; continue; } /* * Trivial optimization: if we find an entry that * already matches the sub-directory, then we know * we're ok, and we can exit. */ for (; pos < index->entries.length; ++pos) { struct entry_internal *p = index->entries.contents[pos]; if (p->pathlen <= len || p->path[len] != '/' || memcmp(p->path, name, len)) break; /* not our subdirectory */ if (GIT_IDXENTRY_STAGE(&p->entry) == stage) return retval; } } return retval; } Commit Message: index: convert `read_entry` to return entry size via an out-param The function `read_entry` does not conform to our usual coding style of returning stuff via the out parameter and to use the return value for reporting errors. Due to most of our code conforming to that pattern, it has become quite natural for us to actually return `-1` in case there is any error, which has also slipped in with commit 5625d86b9 (index: support index v4, 2016-05-17). As the function returns an `size_t` only, though, the return value is wrapped around, causing the caller of `read_tree` to continue with an invalid index entry. Ultimately, this can lead to a double-free. Improve code and fix the bug by converting the function to return the index entry size via an out parameter and only using the return value to indicate errors. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-415 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 ExtensionTtsPlatformImpl::set_error(const std::string& error) { error_ = error; } 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 Target: 1 Example 2: Code: void dispatchInputEvent(Element* target, InputEvent::InputType inputType, const String& data, InputEvent::EventIsComposing isComposing) { if (!RuntimeEnabledFeatures::inputEventEnabled()) return; if (!target) return; InputEvent* inputEvent = InputEvent::createInput(inputType, data, isComposing, nullptr); target->dispatchScopedEvent(inputEvent); } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} 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 sas_eh_defer_cmd(struct scsi_cmnd *cmd) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_ha_struct *ha = dev->port->ha; struct sas_task *task = TO_SAS_TASK(cmd); if (!dev_is_sata(dev)) { sas_eh_finish_cmd(cmd); return; } /* report the timeout to libata */ sas_end_task(cmd, task); list_move_tail(&cmd->eh_entry, &ha->eh_ata_q); } Commit Message: scsi: libsas: defer ata device eh commands to libata When ata device doing EH, some commands still attached with tasks are not passed to libata when abort failed or recover failed, so libata did not handle these commands. After these commands done, sas task is freed, but ata qc is not freed. This will cause ata qc leak and trigger a warning like below: WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037 ata_eh_finish+0xb4/0xcc CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1 ...... Call trace: [<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc [<ffff0000088b8420>] ata_do_eh+0xc4/0xd8 [<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c [<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694 [<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80 [<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170 [<ffff0000080ebd70>] process_one_work+0x144/0x390 [<ffff0000080ec100>] worker_thread+0x144/0x418 [<ffff0000080f2c98>] kthread+0x10c/0x138 [<ffff0000080855dc>] ret_from_fork+0x10/0x18 If ata qc leaked too many, ata tag allocation will fail and io blocked for ever. As suggested by Dan Williams, defer ata device commands to libata and merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle ata qcs correctly after this. Signed-off-by: Jason Yan <[email protected]> CC: Xiaofei Tan <[email protected]> CC: John Garry <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Dan Williams <[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: iperf_json_printf(const char *format, ...) { cJSON* o; va_list argp; const char *cp; char name[100]; char* np; cJSON* j; o = cJSON_CreateObject(); if (o == NULL) return NULL; va_start(argp, format); np = name; for (cp = format; *cp != '\0'; ++cp) { switch (*cp) { case ' ': break; case ':': *np = '\0'; break; case '%': ++cp; switch (*cp) { case 'b': j = cJSON_CreateBool(va_arg(argp, int)); break; case 'd': j = cJSON_CreateInt(va_arg(argp, int64_t)); break; case 'f': j = cJSON_CreateFloat(va_arg(argp, double)); break; case 's': j = cJSON_CreateString(va_arg(argp, char *)); break; default: return NULL; } if (j == NULL) return NULL; cJSON_AddItemToObject(o, name, j); np = name; break; default: *np++ = *cp; break; } } va_end(argp); return o; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void ProfileSyncService::UpdateLastSyncedTime() { last_synced_time_ = base::Time::Now(); sync_prefs_.SetLastSyncedTime(last_synced_time_); } 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: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } Commit Message: Fail expression lookup on invalid atoms If we fail atom lookup, then we should not claim that we successfully looked up the expression. Signed-off-by: Daniel Stone <[email protected]> CWE ID: CWE-476 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 run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dump_dir_accessible_by_uid(dirname, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dirname); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid); return 403; /* Forbidden */ } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void CWebServer::RType_TransferDevice(WebEmSession & session, const request& req, Json::Value &root) { std::string sidx = request::findValue(&req, "idx"); if (sidx.empty()) return; std::string newidx = request::findValue(&req, "newidx"); if (newidx.empty()) return; std::vector<std::vector<std::string> > result; time_t now = mytime(NULL); struct tm tm1; localtime_r(&now, &tm1); struct tm LastUpdateTime_A; struct tm LastUpdateTime_B; result = m_sql.safe_query( "SELECT A.LastUpdate, B.LastUpdate FROM DeviceStatus as A, DeviceStatus as B WHERE (A.ID == '%q') AND (B.ID == '%q')", sidx.c_str(), newidx.c_str()); if (result.empty()) return; std::string sLastUpdate_A = result[0][0]; std::string sLastUpdate_B = result[0][1]; time_t timeA, timeB; ParseSQLdatetime(timeA, LastUpdateTime_A, sLastUpdate_A, tm1.tm_isdst); ParseSQLdatetime(timeB, LastUpdateTime_B, sLastUpdate_B, tm1.tm_isdst); if (timeA < timeB) { sidx.swap(newidx); } result = m_sql.safe_query( "SELECT HardwareID, DeviceID, Unit, Name, Type, SubType, SignalLevel, BatteryLevel, nValue, sValue FROM DeviceStatus WHERE (ID == '%q')", newidx.c_str()); if (result.empty()) return; root["status"] = "OK"; root["title"] = "TransferDevice"; m_sql.TransferDevice(newidx, sidx); m_sql.DeleteDevices(newidx); m_mainworker.m_scheduler.ReloadSchedules(); } Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!) CWE ID: CWE-89 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 AXLayoutObject::addChildren() { ASSERT(!isDetached()); ASSERT(!m_haveChildren); m_haveChildren = true; if (!canHaveChildren()) return; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) { obj->setParent(this); addChild(obj); } } addHiddenChildren(); addPopupChildren(); addImageMapChildren(); addTextFieldChildren(); addCanvasChildren(); addRemoteSVGChildren(); addInlineTextBoxChildren(false); for (const auto& child : m_children) { if (!child->cachedParentObject()) child->setParent(this); } for (const auto& ownedChild : ownedChildren) addChild(ownedChild); } 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 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 PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } 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: ResourceDispatcherHostImpl::LoadInfo::~LoadInfo() {} 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: 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 l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_unused = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } Commit Message: l2tp: fix info leak in l2tp_ip6_recvmsg() The L2TP code for IPv6 fails to initialize the l2tp_conn_id member of struct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack in l2tp_ip6_recvmsg() in case msg_name is set. Initialize l2tp_conn_id with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 BluetoothDeviceChromeOS::OnRegisterAgent( const base::Closure& callback, const ConnectErrorCallback& error_callback) { VLOG(1) << object_path_.value() << ": Agent registered, now pairing"; DBusThreadManager::Get()->GetBluetoothDeviceClient()-> Pair(object_path_, base::Bind(&BluetoothDeviceChromeOS::OnPair, weak_ptr_factory_.GetWeakPtr(), callback, error_callback), base::Bind(&BluetoothDeviceChromeOS::OnPairError, weak_ptr_factory_.GetWeakPtr(), error_callback)); } 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: static INT AirPDcapScanForKeys( PAIRPDCAP_CONTEXT ctx, const guint8 *data, const guint mac_header_len, const guint tot_len, AIRPDCAP_SEC_ASSOCIATION_ID id ) { const UCHAR *addr; guint bodyLength; PAIRPDCAP_SEC_ASSOCIATION sta_sa; PAIRPDCAP_SEC_ASSOCIATION sa; guint offset = 0; const guint8 dot1x_header[] = { 0xAA, /* DSAP=SNAP */ 0xAA, /* SSAP=SNAP */ 0x03, /* Control field=Unnumbered frame */ 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ 0x88, 0x8E /* Type: 802.1X authentication */ }; const guint8 bt_dot1x_header[] = { 0xAA, /* DSAP=SNAP */ 0xAA, /* SSAP=SNAP */ 0x03, /* Control field=Unnumbered frame */ 0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */ 0x00, 0x03 /* Type: Bluetooth Security */ }; const guint8 tdls_header[] = { 0xAA, /* DSAP=SNAP */ 0xAA, /* SSAP=SNAP */ 0x03, /* Control field=Unnumbered frame */ 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ 0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */ 0x02, /* Payload Type: TDLS */ 0X0C /* Action Category: TDLS */ }; const EAPOL_RSN_KEY *pEAPKey; #ifdef _DEBUG #define MSGBUF_LEN 255 CHAR msgbuf[MSGBUF_LEN]; #endif AIRPDCAP_DEBUG_TRACE_START("AirPDcapScanForKeys"); /* cache offset in the packet data */ offset = mac_header_len; /* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */ if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3); /* skip LLC header */ offset+=8; /* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */ if (data[offset+1]!=3) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not EAPOL-Key", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* get and check the body length (IEEE 802.1X-2004, pg. 25) */ bodyLength=pntoh16(data+offset+2); if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */ AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "EAPOL body too short", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* skip EAPOL MPDU and go to the first byte of the body */ offset+=4; pEAPKey = (const EAPOL_RSN_KEY *) (data+offset); /* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */ if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */ pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */ pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */ { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not valid key descriptor type", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* start with descriptor body */ offset+=1; /* search for a cached Security Association for current BSSID and AP */ sa = AirPDcapGetSaPtr(ctx, &id); if (sa == NULL){ AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "No SA for BSSID found", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_REQ_DATA; } /* It could be a Pairwise Key exchange, check */ if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE) return AIRPDCAP_RET_SUCCESS_HANDSHAKE; if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Message too short for Group Key", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */ if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 || AIRPDCAP_EAP_ACK(data[offset+1])!=1 || AIRPDCAP_EAP_MIC(data[offset]) != 1 || AIRPDCAP_EAP_SEC(data[offset]) != 1){ AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Key bitfields not correct for Group Key", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* force STA address to be the broadcast MAC so we create an SA for the groupkey */ memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN); /* get the Security Association structure for the broadcast MAC and AP */ sa = AirPDcapGetSaPtr(ctx, &id); if (sa == NULL){ return AIRPDCAP_RET_REQ_DATA; } /* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */ /* get STA address */ if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) { memcpy(id.sta, addr, AIRPDCAP_MAC_LEN); #ifdef _DEBUG g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]); #endif AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", msgbuf, AIRPDCAP_DEBUG_LEVEL_3); } else { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "SA not found", AIRPDCAP_DEBUG_LEVEL_5); return AIRPDCAP_RET_REQ_DATA; } sta_sa = AirPDcapGetSaPtr(ctx, &id); if (sta_sa == NULL){ return AIRPDCAP_RET_REQ_DATA; } /* Try to extract the group key and install it in the SA */ return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1)); } else if (memcmp(data+offset, tdls_header, 10) == 0) { const guint8 *initiator, *responder; guint8 action; guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0; AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: TDLS Action Frame", AIRPDCAP_DEBUG_LEVEL_3); /* skip LLC header */ offset+=10; /* check if the packet is a TDLS response or confirm */ action = data[offset]; if (action!=1 && action!=2) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not Response nor confirm", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* check status */ offset++; status=pntoh16(data+offset); if (status!=0) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "TDLS setup not successfull", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* skip Token + capabilities */ offset+=5; /* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */ while(offset < (tot_len - 2)) { if (data[offset] == 48) { offset_rsne = offset; } else if (data[offset] == 55) { offset_fte = offset; } else if (data[offset] == 56) { offset_timeout = offset; } else if (data[offset] == 101) { offset_link = offset; } if (tot_len < offset + data[offset + 1] + 2) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } offset += data[offset + 1] + 2; } if (offset_rsne == 0 || offset_fte == 0 || offset_timeout == 0 || offset_link == 0) { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Cannot Find all necessary IEs", AIRPDCAP_DEBUG_LEVEL_3); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Found RSNE/Fast BSS/Timeout Interval/Link IEs", AIRPDCAP_DEBUG_LEVEL_3); /* Will create a Security Association between 2 STA. Need to get both MAC address */ initiator = &data[offset_link + 8]; responder = &data[offset_link + 14]; if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) { memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN); memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN); } else { memcpy(id.sta, responder, AIRPDCAP_MAC_LEN); memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN); } sa = AirPDcapGetSaPtr(ctx, &id); if (sa == NULL){ return AIRPDCAP_RET_REQ_DATA; } if (sa->validKey) { if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) { /* Already have valid key for this SA, no need to redo key derivation */ return AIRPDCAP_RET_SUCCESS_HANDSHAKE; } else { /* We are opening a new session with the same two STA, save previous sa */ AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1); memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); sa->next=tmp_sa; sa->validKey = FALSE; } } if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action) == AIRPDCAP_RET_SUCCESS) { AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys"); return AIRPDCAP_RET_SUCCESS_HANDSHAKE; } } else { AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Skipping: not an EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3); } AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys"); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } Commit Message: Sanity check eapol_len in AirPDcapDecryptWPABroadcastKey Bug: 12175 Change-Id: Iaf977ba48f8668bf8095800a115ff9a3472dd893 Reviewed-on: https://code.wireshark.org/review/15326 Petri-Dish: Michael Mann <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Alexis La Goutte <[email protected]> Reviewed-by: Peter Wu <[email protected]> Tested-by: Peter Wu <[email protected]> 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: SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Output:
1