Dataset Viewer
Auto-converted to Parquet
instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; } 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
unsigned long long Track::GetSeekPreRoll() const
174,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: test_js (void) { GString *result = g_string_new(""); /* simple javascript can be evaluated and returned */ parse_cmd_line("js ('x' + 345).toUpperCase()", result); g_assert_cmpstr("X345", ==, result->str); /* uzbl commands can be run from javascript */ uzbl.net.useragent = "Test useragent"; parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result); g_assert_cmpstr("TEST USERAGENT", ==, result->str); g_string_free(result, TRUE); } Commit Message: disable Uzbl javascript object because of security problem. CWE ID: CWE-264
test_js (void) { GString *result = g_string_new(""); /* simple javascript can be evaluated and returned */ parse_cmd_line("js ('x' + 345).toUpperCase()", result); g_assert_cmpstr("X345", ==, result->str); g_string_free(result, TRUE); }
165,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int __init init_ext2_fs(void) { int err = init_ext2_xattr(); if (err) return err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); out1: exit_ext2_xattr(); return err; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
static int __init init_ext2_fs(void) { int err; err = init_inodecache(); if (err) return err; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); return err; }
169,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: XdmcpGenerateKey (XdmAuthKeyPtr key) { #ifndef HAVE_ARC4RANDOM_BUF long lowbits, highbits; srandom ((int)getpid() ^ time((Time_t *)0)); highbits = random (); highbits = random (); getbits (lowbits, key->data); getbits (highbits, key->data + 4); #else arc4random_buf(key->data, 8); #endif } Commit Message: CWE ID: CWE-320
XdmcpGenerateKey (XdmAuthKeyPtr key) #ifndef HAVE_ARC4RANDOM_BUF static void emulate_getrandom_buf (char *auth, int len) { long lowbits, highbits; srandom ((int)getpid() ^ time((Time_t *)0)); highbits = random (); highbits = random (); getbits (lowbits, key->data); getbits (highbits, key->data + 4); } static void arc4random_buf (void *auth, int len) { int ret; #if HAVE_GETENTROPY /* weak emulation of arc4random through the getentropy libc call */ ret = getentropy (auth, len); if (ret == 0) return; #endif /* HAVE_GETENTROPY */ emulate_getrandom_buf (auth, len); } #endif /* !defined(HAVE_ARC4RANDOM_BUF) */ void XdmcpGenerateKey (XdmAuthKeyPtr key) { arc4random_buf(key->data, 8); }
165,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) { if (!agent_.get()) return false; bool callback_run = false; if (!pincode_callback_.is_null()) { pincode_callback_.Run(status, ""); pincode_callback_.Reset(); callback_run = true; } if (!passkey_callback_.is_null()) { passkey_callback_.Run(status, 0); passkey_callback_.Reset(); callback_run = true; } if (!confirmation_callback_.is_null()) { confirmation_callback_.Run(status); confirmation_callback_.Reset(); callback_run = true; } return callback_run; } 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:
bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) {
171,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; if (cnt < 0) { jas_deprecated("negative count for jas_stream_write"); } bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; }
168,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } } Commit Message: CWE ID: CWE-189
void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmallocn (length, nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } }
164,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return true; //must assume done if (total < 0) return false; //assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); } 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
bool Segment::DoneParsing() const bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return true; // must assume done if (total < 0) return false; // assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); }
174,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DownloadManagerImpl::DownloadUrl( std::unique_ptr<download::DownloadUrlParameters> params, std::unique_ptr<storage::BlobDataHandle> blob_data_handle, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) { if (params->post_id() >= 0) { DCHECK(params->prefer_cache()); DCHECK_EQ("POST", params->method()); } download::RecordDownloadCountWithSource( download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT, params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL()); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
void DownloadManagerImpl::DownloadUrl( std::unique_ptr<download::DownloadUrlParameters> params, std::unique_ptr<storage::BlobDataHandle> blob_data_handle, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) { if (params->post_id() >= 0) { DCHECK(params->prefer_cache()); DCHECK_EQ("POST", params->method()); } download::RecordDownloadCountWithSource( download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT, params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); if (rfh) params->set_frame_tree_node_id(rfh->GetFrameTreeNodeId()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL()); }
173,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void TabStrip::ChangeTabGroup(int model_index, base::Optional<int> old_group, base::Optional<int> new_group) { if (new_group.has_value() && !group_headers_[new_group.value()]) { const TabGroupData* group_data = controller_->GetDataForGroup(new_group.value()); auto header = std::make_unique<TabGroupHeader>(group_data->title()); header->set_owned_by_client(); AddChildView(header.get()); group_headers_[new_group.value()] = std::move(header); } if (old_group.has_value() && controller_->ListTabsInGroup(old_group.value()).size() == 0) { group_headers_.erase(old_group.value()); } UpdateIdealBounds(); AnimateToIdealBounds(); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void TabStrip::ChangeTabGroup(int model_index, base::Optional<int> old_group, base::Optional<int> new_group) { tab_at(model_index)->SetGroup(new_group); if (new_group.has_value() && !group_headers_[new_group.value()]) { auto header = std::make_unique<TabGroupHeader>(this, new_group.value()); header->set_owned_by_client(); AddChildView(header.get()); group_headers_[new_group.value()] = std::move(header); } if (old_group.has_value() && controller_->ListTabsInGroup(old_group.value()).size() == 0) { group_headers_.erase(old_group.value()); } UpdateIdealBounds(); AnimateToIdealBounds(); }
172,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, unsigned int b, unsigned int a, unsigned int in_digitized, double in, unsigned int out, png_byte sample_depth, double err, double limit, PNG_CONST char *name, double digitization_error) { /* Compare the scaled, digitzed, values of our local calculation (in+-err) * with the digitized values libpng produced; 'sample_depth' is the actual * digitization depth of the libpng output colors (the bit depth except for * palette images where it is always 8.) The check on 'err' is to detect * internal errors in pngvalid itself. */ unsigned int max = (1U<<sample_depth)-1; double in_min = ceil((in-err)*max - digitization_error); double in_max = floor((in+err)*max + digitization_error); if (err > limit || !(out >= in_min && out <= in_max)) { char message[256]; size_t pos; pos = safecat(message, sizeof message, 0, name); pos = safecat(message, sizeof message, pos, " output value error: rgba("); pos = safecatn(message, sizeof message, pos, r); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, g); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, b); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, a); pos = safecat(message, sizeof message, pos, "): "); pos = safecatn(message, sizeof message, pos, out); pos = safecat(message, sizeof message, pos, " expected: "); pos = safecatn(message, sizeof message, pos, in_digitized); pos = safecat(message, sizeof message, pos, " ("); pos = safecatd(message, sizeof message, pos, (in-err)*max, 3); pos = safecat(message, sizeof message, pos, ".."); pos = safecatd(message, sizeof message, pos, (in+err)*max, 3); pos = safecat(message, sizeof message, pos, ")"); png_error(pp, message); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, unsigned int b, unsigned int a, unsigned int in_digitized, double in, unsigned int out, png_byte sample_depth, double err, double limit, const char *name, double digitization_error) { /* Compare the scaled, digitzed, values of our local calculation (in+-err) * with the digitized values libpng produced; 'sample_depth' is the actual * digitization depth of the libpng output colors (the bit depth except for * palette images where it is always 8.) The check on 'err' is to detect * internal errors in pngvalid itself. */ unsigned int max = (1U<<sample_depth)-1; double in_min = ceil((in-err)*max - digitization_error); double in_max = floor((in+err)*max + digitization_error); if (err > limit || !(out >= in_min && out <= in_max)) { char message[256]; size_t pos; pos = safecat(message, sizeof message, 0, name); pos = safecat(message, sizeof message, pos, " output value error: rgba("); pos = safecatn(message, sizeof message, pos, r); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, g); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, b); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, a); pos = safecat(message, sizeof message, pos, "): "); pos = safecatn(message, sizeof message, pos, out); pos = safecat(message, sizeof message, pos, " expected: "); pos = safecatn(message, sizeof message, pos, in_digitized); pos = safecat(message, sizeof message, pos, " ("); pos = safecatd(message, sizeof message, pos, (in-err)*max, 3); pos = safecat(message, sizeof message, pos, ".."); pos = safecatd(message, sizeof message, pos, (in+err)*max, 3); pos = safecat(message, sizeof message, pos, ")"); png_error(pp, message); } }
173,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { struct crypto_rng *rng = __crypto_rng_cast(tfm); struct rng_alg *alg = crypto_rng_alg(rng); struct old_rng_alg *oalg = crypto_old_rng_alg(rng); if (oalg->rng_make_random) { rng->generate = generate; rng->seed = rngapi_reset; rng->seedsize = oalg->seedsize; return 0; } rng->generate = alg->generate; rng->seed = alg->seed; rng->seedsize = alg->seedsize; return 0; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { return 0; }
167,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: IceGenerateMagicCookie ( int len ) { char *auth; #ifndef HAVE_ARC4RANDOM_BUF long ldata[2]; int seed; int value; int i; #endif if ((auth = malloc (len + 1)) == NULL) return (NULL); #ifdef HAVE_ARC4RANDOM_BUF arc4random_buf(auth, len); #else #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; } Commit Message: CWE ID: CWE-331
IceGenerateMagicCookie ( static void emulate_getrandom_buf ( char *auth, int len ) { long ldata[2]; int seed; int value; int i; #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else /* ITIMER_REAL */ { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif /* ITIMER_REAL */ seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; }
165,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save, NULL); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
void btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save_cb, NULL); }
173,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; } Commit Message: Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes. CWE ID: CWE-119
static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; }
167,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static uint64_t ReadBits(BitReader* reader, int num_bits) { DCHECK_GE(reader->bits_available(), num_bits); DCHECK((num_bits > 0) && (num_bits <= 64)); uint64_t value; reader->ReadBits(num_bits, &value); return value; } Commit Message: Cleanup media BitReader ReadBits() calls Initialize temporary values, check return values. Small tweaks to solution proposed by adtolbar@microsoft.com. Bug: 929962 Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735 Reviewed-on: https://chromium-review.googlesource.com/c/1481085 Commit-Queue: Chrome Cunningham <chcunningham@chromium.org> Reviewed-by: Dan Sanders <sandersd@chromium.org> Cr-Commit-Position: refs/heads/master@{#634889} CWE ID: CWE-200
static uint64_t ReadBits(BitReader* reader, int num_bits) { DCHECK_GE(reader->bits_available(), num_bits); DCHECK((num_bits > 0) && (num_bits <= 64)); uint64_t value = 0; if (!reader->ReadBits(num_bits, &value)) return 0; return value; }
173,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_maps); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_map_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; } 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
static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_rw_ctxts); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_rw_ctxt_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; }
168,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: header_put_marker (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_marker */ 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
header_put_marker (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_marker */
170,059
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <radimre83@gmail.com> CWE ID: CWE-400
gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); gss_release_buffer(&min, &in); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } gss_release_buffer(&min, &out); GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; }
169,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return 0; if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1; *in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); *out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); return 0; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out) uint32_t GetPayloadTime(size_t handle, uint32_t index, double *in, double *out) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return GPMF_ERROR_MEMORY; if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return GPMF_ERROR_MEMORY; *in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); *out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); return GPMF_OK; }
169,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; } Commit Message: Merge branch 'security' into 'master' Security Closes #10 See merge request !17 CWE ID: CWE-416
char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); if (tm == NULL) return g_strdup("???"); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; }
168,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) { unsigned int cpy_len, rem_len; uint32_t list_len; uint8_t* p; uint8_t type; #if (SDP_DEBUG_RAW == TRUE) uint8_t num_array[SDP_MAX_LIST_BYTE_COUNT]; uint32_t i; for (i = 0; i < p_ccb->list_len; i++) { snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", (uint8_t)(p_ccb->rsp_list[i])); } SDP_TRACE_WARNING("result :%s", num_array); #endif if (p_ccb->p_db->raw_data) { cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used; list_len = p_ccb->list_len; p = &p_ccb->rsp_list[0]; if (offset) { type = *p++; p = sdpu_get_len_from_type(p, type, &list_len); } if (list_len < cpy_len) { cpy_len = list_len; } rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]); if (cpy_len > rem_len) { SDP_TRACE_WARNING("rem_len :%d less than cpy_len:%d", rem_len, cpy_len); cpy_len = rem_len; } SDP_TRACE_WARNING( "%s: list_len:%d cpy_len:%d p:%p p_ccb:%p p_db:%p raw_size:%d " "raw_used:%d raw_data:%p", __func__, list_len, cpy_len, p, p_ccb, p_ccb->p_db, p_ccb->p_db->raw_size, p_ccb->p_db->raw_used, p_ccb->p_db->raw_data); memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); p_ccb->p_db->raw_used += cpy_len; } } Commit Message: Fix copy length calculation in sdp_copy_raw_data Test: compilation Bug: 110216176 Change-Id: Ic4a19c9f0fe8cd592bc6c25dcec7b1da49ff7459 (cherry picked from commit 23aa15743397b345f3d948289fe90efa2a2e2b3e) CWE ID: CWE-787
static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) { unsigned int cpy_len, rem_len; uint32_t list_len; uint8_t* p; uint8_t type; #if (SDP_DEBUG_RAW == TRUE) uint8_t num_array[SDP_MAX_LIST_BYTE_COUNT]; uint32_t i; for (i = 0; i < p_ccb->list_len; i++) { snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", (uint8_t)(p_ccb->rsp_list[i])); } SDP_TRACE_WARNING("result :%s", num_array); #endif if (p_ccb->p_db->raw_data) { cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used; list_len = p_ccb->list_len; p = &p_ccb->rsp_list[0]; if (offset) { cpy_len -= 1; type = *p++; uint8_t* old_p = p; p = sdpu_get_len_from_type(p, type, &list_len); if ((int)cpy_len < (p - old_p)) { SDP_TRACE_WARNING("%s: no bytes left for data", __func__); return; } cpy_len -= (p - old_p); } if (list_len < cpy_len) { cpy_len = list_len; } rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]); if (cpy_len > rem_len) { SDP_TRACE_WARNING("rem_len :%d less than cpy_len:%d", rem_len, cpy_len); cpy_len = rem_len; } SDP_TRACE_WARNING( "%s: list_len:%d cpy_len:%d p:%p p_ccb:%p p_db:%p raw_size:%d " "raw_used:%d raw_data:%p", __func__, list_len, cpy_len, p, p_ccb, p_ccb->p_db, p_ccb->p_db->raw_size, p_ccb->p_db->raw_used, p_ccb->p_db->raw_data); memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); p_ccb->p_db->raw_used += cpy_len; } }
174,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool DownloadItemImpl::CanOpenDownload() { const bool is_complete = GetState() == DownloadItem::COMPLETE; return (!IsDone() || is_complete) && !IsTemporary() && !file_externally_removed_; } 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 <dtrainor@chromium.org> Reviewed-by: Xing Liu <xingliu@chromium.org> Reviewed-by: John Abd-El-Malek <jam@chromium.org> Commit-Queue: Shakti Sahu <shaktisahu@chromium.org> Cr-Commit-Position: refs/heads/master@{#525810} CWE ID: CWE-20
bool DownloadItemImpl::CanOpenDownload() { const bool is_complete = GetState() == DownloadItem::COMPLETE; return (!IsDone() || is_complete) && !IsTemporary() && !file_externally_removed_ && delegate_->IsMostRecentDownloadItemAtFilePath(this); }
172,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, struct flowi *fl, struct request_sock *req, struct tcp_fastopen_cookie *foc, bool attach_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &fl->u.ip6; struct sk_buff *skb; int err = -ENOMEM; /* First, grab a route. */ if (!dst && (dst = inet6_csk_route_req(sk, fl6, req, IPPROTO_TCP)) == NULL) goto done; skb = tcp_make_synack(sk, dst, req, foc, attach_req); if (skb) { __tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; if (np->repflow && ireq->pktopts) fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); err = ip6_xmit(sk, skb, fl6, np->opt, np->tclass); err = net_xmit_eval(err); } done: return err; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, struct flowi *fl, struct request_sock *req, struct tcp_fastopen_cookie *foc, bool attach_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &fl->u.ip6; struct sk_buff *skb; int err = -ENOMEM; /* First, grab a route. */ if (!dst && (dst = inet6_csk_route_req(sk, fl6, req, IPPROTO_TCP)) == NULL) goto done; skb = tcp_make_synack(sk, dst, req, foc, attach_req); if (skb) { __tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; if (np->repflow && ireq->pktopts) fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); err = ip6_xmit(sk, skb, fl6, rcu_dereference(np->opt), np->tclass); err = net_xmit_eval(err); } done: return err; }
167,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Chapters::Atom::ParseDisplay( IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } 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
long Chapters::Atom::ParseDisplay(
174,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Segment::LoadCluster( long long& pos, long& len) { for (;;) { const long result = DoLoadCluster(pos, len); if (result <= 1) return result; } } 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
long Segment::LoadCluster( if (result <= 1) return result; } } long Segment::DoLoadCluster(long long& pos, long& len) { if (m_pos < 0) return DoLoadClusterUnknownSize(pos, len); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long cluster_off = -1; // offset relative to start of segment long long cluster_size = -1; // size of cluster payload for (;;) { if ((total >= 0) && (m_pos >= total)) return 1; // no more clusters if ((segment_stop >= 0) && (m_pos >= segment_stop)) return 1; // no more clusters pos = m_pos; // Read ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; }
174,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ASessionDescription::getDimensions( size_t index, unsigned long PT, int32_t *width, int32_t *height) const { *width = 0; *height = 0; char key[20]; sprintf(key, "a=framesize:%lu", PT); AString value; if (!findAttribute(index, key, &value)) { return false; } const char *s = value.c_str(); char *end; *width = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '-'); s = end + 1; *height = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '\0'); return true; } Commit Message: Fix corruption via buffer overflow in mediaserver change unbound sprintf() to snprintf() so network-provided values can't overflow the buffers. Applicable to all K/L/M/N branches. Bug: 25747670 Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6 CWE ID: CWE-284
bool ASessionDescription::getDimensions( size_t index, unsigned long PT, int32_t *width, int32_t *height) const { *width = 0; *height = 0; char key[33]; snprintf(key, sizeof(key), "a=framesize:%lu", PT); if (PT > 9999999) { android_errorWriteLog(0x534e4554, "25747670"); } AString value; if (!findAttribute(index, key, &value)) { return false; } const char *s = value.c_str(); char *end; *width = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '-'); s = end + 1; *height = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '\0'); return true; }
173,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); treeScope()->adoptIfNeeded(attrNode); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); }
171,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle) { NOTIMPLEMENTED(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel, void RenderWidgetHostViewGuest::AcceleratedSurfaceNew( int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle, const std::string& mailbox_name) { NOTIMPLEMENTED(); }
171,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) { if (style->templatesHash != NULL) xmlHashFree((xmlHashTablePtr) style->templatesHash, (xmlHashDeallocator) xsltFreeCompMatchList); if (style->rootMatch != NULL) xsltFreeCompMatchList(style->rootMatch); if (style->keyMatch != NULL) xsltFreeCompMatchList(style->keyMatch); if (style->elemMatch != NULL) xsltFreeCompMatchList(style->elemMatch); if (style->attrMatch != NULL) xsltFreeCompMatchList(style->attrMatch); if (style->parentMatch != NULL) xsltFreeCompMatchList(style->parentMatch); if (style->textMatch != NULL) xsltFreeCompMatchList(style->textMatch); if (style->piMatch != NULL) xsltFreeCompMatchList(style->piMatch); if (style->commentMatch != NULL) xsltFreeCompMatchList(style->commentMatch); } 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
xsltFreeTemplateHashes(xsltStylesheetPtr style) { if (style->templatesHash != NULL) xmlHashFree((xmlHashTablePtr) style->templatesHash, (xmlHashDeallocator) xsltFreeCompMatchList); if (style->rootMatch != NULL) xsltFreeCompMatchList(style->rootMatch); if (style->keyMatch != NULL) xsltFreeCompMatchList(style->keyMatch); if (style->elemMatch != NULL) xsltFreeCompMatchList(style->elemMatch); if (style->attrMatch != NULL) xsltFreeCompMatchList(style->attrMatch); if (style->parentMatch != NULL) xsltFreeCompMatchList(style->parentMatch); if (style->textMatch != NULL) xsltFreeCompMatchList(style->textMatch); if (style->piMatch != NULL) xsltFreeCompMatchList(style->piMatch); if (style->commentMatch != NULL) xsltFreeCompMatchList(style->commentMatch); if (style->namedTemplates != NULL) xmlHashFree(style->namedTemplates, NULL); }
173,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629 CWE ID: CWE-369
MagickExport void RemoveDuplicateLayers(Image **images, MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second); time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); }
170,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DataReductionProxyConfig::SecureProxyCheck( SecureProxyCheckerCallback fetcher_callback) { secure_proxy_checker_->CheckIfSecureProxyIsAllowed(fetcher_callback); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void DataReductionProxyConfig::SecureProxyCheck( SecureProxyCheckerCallback fetcher_callback) { if (params::IsIncludedInHoldbackFieldTrial()) return; secure_proxy_checker_->CheckIfSecureProxyIsAllowed(fetcher_callback); }
172,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->SetRenderer(frame_host_ ? frame_host_->GetProcess() : nullptr, frame_host_); protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler())); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); if (frame_tree_node_ && !frame_tree_node_->parent()) { session->AddHandler( base::WrapUnique(new protocol::PageHandler(emulation_handler))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); } if (EnsureAgent()) session->AttachToAgent(agent_ptr_); if (sessions().size() == 1) { frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID() : ChildProcessHost::kInvalidUniqueID, frame_host_); protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler())); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); if (frame_tree_node_ && !frame_tree_node_->parent()) { session->AddHandler( base::WrapUnique(new protocol::PageHandler(emulation_handler))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); } if (EnsureAgent()) session->AttachToAgent(agent_ptr_); if (sessions().size() == 1) { frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } }
172,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); 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:
image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, image_transform_png_set_gray_to_rgb_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); /* NOTE: this doesn't result in tRNS expansion. */ this->next->set(this->next, that, pp, pi); }
173,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek (ifp, 8, SEEK_CUR); foveon_huff (huff); roff[0] = 48; FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek (ifp, data_offset+roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row*width+col][c] = hpred[col & 1]; } } } } Commit Message: Fixed possible foveon buffer overrun (Secunia SA750000) CWE ID: CWE-119
void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[1024], vpred[2][2], hpred[2]; fseek (ifp, 8, SEEK_CUR); foveon_huff (huff); roff[0] = 48; FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek (ifp, data_offset+roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row*width+col][c] = hpred[col & 1]; } } } }
168,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { unsigned int len; unsigned long start=0, off; struct au1200fb_device *fbdev = info->par; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) { return -EINVAL; } start = fbdev->fb_phys & PAGE_MASK; len = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len); off = vma->vm_pgoff << PAGE_SHIFT; if ((vma->vm_end - vma->vm_start + off) > len) { return -EINVAL; } off += start; vma->vm_pgoff = off >> PAGE_SHIFT; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <nico@ngolde.de> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org. CWE ID: CWE-119
static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { struct au1200fb_device *fbdev = info->par; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len); }
165,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsSecure && !audio) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; }
173,763
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::DictionaryValue* val) const { v8::Local<v8::Object> result(v8::Object::New(isolate)); for (base::DictionaryValue::Iterator iter(*val); !iter.IsAtEnd(); iter.Advance()) { const std::string& key = iter.key(); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, &iter.value()); CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch(isolate); result->Set( v8::String::NewFromUtf8( isolate, key.c_str(), v8::String::kNormalString, key.length()), child_v8); if (try_catch.HasCaught()) { LOG(ERROR) << "Setter for property " << key.c_str() << " threw an " << "exception."; } } return result; } Commit Message: V8ValueConverter::ToV8Value should not trigger setters BUG=606390 Review URL: https://codereview.chromium.org/1918793003 Cr-Commit-Position: refs/heads/master@{#390045} CWE ID:
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::DictionaryValue* val) const { v8::Local<v8::Object> result(v8::Object::New(isolate)); // TODO(robwu): Callers should pass in the context. v8::Local<v8::Context> context = isolate->GetCurrentContext(); for (base::DictionaryValue::Iterator iter(*val); !iter.IsAtEnd(); iter.Advance()) { const std::string& key = iter.key(); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, &iter.value()); CHECK(!child_v8.IsEmpty()); v8::Maybe<bool> maybe = result->CreateDataProperty( context, v8::String::NewFromUtf8(isolate, key.c_str(), v8::String::kNormalString, key.length()), child_v8); if (!maybe.IsJust() || !maybe.FromJust()) LOG(ERROR) << "Failed to set property with key " << key; } return result; }
173,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No 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 <viro@zeniv.linux.org.uk> CWE ID: CWE-17
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(); percpu_counter_init(&nr_files, 0); }
166,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr, int flags, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct nfs4_state *state; struct rpc_cred *cred; int status = 0; cred = rpc_lookup_cred(); if (IS_ERR(cred)) { status = PTR_ERR(cred); goto out; } state = nfs4_do_open(dir, &path, flags, sattr, cred); d_drop(dentry); if (IS_ERR(state)) { status = PTR_ERR(state); goto out_putcred; } d_add(dentry, igrab(state->inode)); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); if (flags & O_EXCL) { struct nfs_fattr fattr; status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state); if (status == 0) nfs_setattr_update_inode(state->inode, sattr); nfs_post_op_update_inode(state->inode, &fattr); } if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0) status = nfs4_intent_set_file(nd, &path, state); else nfs4_close_sync(&path, state, flags); out_putcred: put_rpccred(cred); out: return status; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr, int flags, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct nfs4_state *state; struct rpc_cred *cred; fmode_t fmode = flags & (FMODE_READ | FMODE_WRITE); int status = 0; cred = rpc_lookup_cred(); if (IS_ERR(cred)) { status = PTR_ERR(cred); goto out; } state = nfs4_do_open(dir, &path, fmode, flags, sattr, cred); d_drop(dentry); if (IS_ERR(state)) { status = PTR_ERR(state); goto out_putcred; } d_add(dentry, igrab(state->inode)); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); if (flags & O_EXCL) { struct nfs_fattr fattr; status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state); if (status == 0) nfs_setattr_update_inode(state->inode, sattr); nfs_post_op_update_inode(state->inode, &fattr); } if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0) status = nfs4_intent_set_file(nd, &path, state, fmode); else nfs4_close_sync(&path, state, fmode); out_putcred: put_rpccred(cred); out: return status; }
165,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect); if (attrName == SVGNames::typeAttr) return colorMatrix->setType(m_type->currentValue()->enumValue()); if (attrName == SVGNames::valuesAttr) return colorMatrix->setValues(m_values->currentValue()->toFloatVector()); ASSERT_NOT_REACHED(); return false; } Commit Message: Explicitly enforce values size in feColorMatrix. R=senorblanco@chromium.org 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:
bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect); if (attrName == SVGNames::typeAttr) return colorMatrix->setType(m_type->currentValue()->enumValue()); if (attrName == SVGNames::valuesAttr) { Vector<float> values = m_values->currentValue()->toFloatVector(); if (values.size() == 20) return colorMatrix->setValues(m_values->currentValue()->toFloatVector()); return false; } ASSERT_NOT_REACHED(); return false; }
171,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UsbDeviceImpl::OpenInterface(int interface_id, const OpenCallback& callback) { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; client->RequestPathAccess( device_path_, interface_id, base::Bind(&UsbDeviceImpl::OnPathAccessRequestComplete, this, callback)); } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
void UsbDeviceImpl::OpenInterface(int interface_id,
171,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } else { ALOGE("b/21657957"); return NULL; } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); }
173,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas, const SkPath& clip) const { bool has_custom_image; int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image); if (!has_custom_image) fill_id = 0; PaintTabBackground(canvas, false /* active */, fill_id, 0, tab_->controller()->MaySetClip() ? &clip : nullptr); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas, const SkPath& clip) const { bool has_custom_image; int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image); if (!has_custom_image) fill_id = 0; PaintTabBackground(canvas, TAB_INACTIVE, fill_id, 0, tab_->controller()->MaySetClip() ? &clip : nullptr); }
172,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNCNameComplex++; #endif /* * Handler for more complex cases */ GROW; c = CUR_CHAR(l); if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!xmlIsNameStartChar(ctxt, c) || (c == ':'))) { return(NULL); } while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ (xmlIsNameChar(ctxt, c) && (c != ':'))) { if (count++ > 100) { count = 0; GROW; } len += l; NEXTL(l); c = CUR_CHAR(l); } return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); } 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
xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNCNameComplex++; #endif /* * Handler for more complex cases */ GROW; c = CUR_CHAR(l); if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!xmlIsNameStartChar(ctxt, c) || (c == ':'))) { return(NULL); } while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ (xmlIsNameChar(ctxt, c) && (c != ':'))) { if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); } return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); }
171,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */ Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that. CWE ID: CWE-400
static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; fpm_globals.listening_socket = dup(wp->listening_socket); if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */
169,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xsltNumberFormat(ctxt, &comp->numdata, node); } 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
xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathContextPtr xpctxt; xmlNsPtr *oldXPNamespaces; int oldXPNsNr; if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xpctxt = ctxt->xpathCtxt; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif xsltNumberFormat(ctxt, &comp->numdata, node); xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; }
173,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationReplaceable()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org 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
static void locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationReplaceable()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int tls1_cbc_remove_padding(const SSL* s, SSL3_RECORD *rec, unsigned block_size, unsigned mac_size) { unsigned padding_length, good, to_check, i; const char has_explicit_iv = s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION; const unsigned overhead = 1 /* padding length byte */ + mac_size + (has_explicit_iv ? block_size : 0); /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > rec->length) return 0; padding_length = rec->data[rec->length-1]; /* NB: if compression is in operation the first packet may not be of padding_length--; } Commit Message: CWE ID: CWE-310
int tls1_cbc_remove_padding(const SSL* s, SSL3_RECORD *rec, unsigned block_size, unsigned mac_size) { unsigned padding_length, good, to_check, i; const char has_explicit_iv = s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION; const unsigned overhead = 1 /* padding length byte */ + mac_size + (has_explicit_iv ? block_size : 0); /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > rec->length) return 0; /* We can always safely skip the explicit IV. We check at the beginning * of this function that the record has at least enough space for the * IV, MAC and padding length byte. (These can be checked in * non-constant time because it's all public information.) So, if the * padding was invalid, then we didn't change |rec->length| and this is * safe. If the padding was valid then we know that we have at least * overhead+padding_length bytes of space and so this is still safe * because overhead accounts for the explicit IV. */ if (has_explicit_iv) { rec->data += block_size; rec->input += block_size; rec->length -= block_size; } padding_length = rec->data[rec->length-1]; /* NB: if compression is in operation the first packet may not be of padding_length--; }
164,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: id3_skip (SF_PRIVATE * psf) { unsigned char buf [10] ; memset (buf, 0, sizeof (buf)) ; psf_binheader_readf (psf, "pb", 0, buf, 10) ; if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3') { int offset = buf [6] & 0x7f ; offset = (offset << 7) | (buf [7] & 0x7f) ; offset = (offset << 7) | (buf [8] & 0x7f) ; offset = (offset << 7) | (buf [9] & 0x7f) ; psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ; /* Never want to jump backwards in a file. */ if (offset < 0) return 0 ; /* Calculate new file offset and position ourselves there. */ psf->fileoffset += offset + 10 ; psf_binheader_readf (psf, "p", psf->fileoffset) ; return 1 ; } ; return 0 ; } /* id3_skip */ Commit Message: src/id3.c : Improve error handling CWE ID: CWE-119
id3_skip (SF_PRIVATE * psf) { unsigned char buf [10] ; memset (buf, 0, sizeof (buf)) ; psf_binheader_readf (psf, "pb", 0, buf, 10) ; if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3') { int offset = buf [6] & 0x7f ; offset = (offset << 7) | (buf [7] & 0x7f) ; offset = (offset << 7) | (buf [8] & 0x7f) ; offset = (offset << 7) | (buf [9] & 0x7f) ; psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ; /* Never want to jump backwards in a file. */ if (offset < 0) return 0 ; /* Calculate new file offset and position ourselves there. */ psf->fileoffset += offset + 10 ; if (psf->fileoffset < psf->filelength) { psf_binheader_readf (psf, "p", psf->fileoffset) ; return 1 ; } ; } ; return 0 ; } /* id3_skip */
168,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderFrameHostImpl::ResetFeaturePolicy() { RenderFrameHostImpl* parent_frame_host = GetParent(); const FeaturePolicy* parent_policy = parent_frame_host ? parent_frame_host->get_feature_policy() : nullptr; ParsedFeaturePolicyHeader container_policy = frame_tree_node()->effective_container_policy(); feature_policy_ = FeaturePolicy::CreateFromParentPolicy( parent_policy, container_policy, last_committed_origin_); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
void RenderFrameHostImpl::ResetFeaturePolicy() { RenderFrameHostImpl* parent_frame_host = GetParent(); const FeaturePolicy* parent_policy = parent_frame_host ? parent_frame_host->feature_policy() : nullptr; ParsedFeaturePolicyHeader container_policy = frame_tree_node()->effective_container_policy(); feature_policy_ = FeaturePolicy::CreateFromParentPolicy( parent_policy, container_policy, last_committed_origin_); }
171,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int TestOpenProcess(DWORD process_id) { HANDLE process = ::OpenProcess(PROCESS_VM_READ, FALSE, // Do not inherit handle. process_id); if (NULL == process) { if (ERROR_ACCESS_DENIED == ::GetLastError()) { return SBOX_TEST_DENIED; } else { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } } else { ::CloseHandle(process); return SBOX_TEST_SUCCEEDED; } } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int TestOpenProcess(DWORD process_id) { int TestOpenProcess(DWORD process_id, DWORD access_mask) { HANDLE process = ::OpenProcess(access_mask, FALSE, // Do not inherit handle. process_id); if (NULL == process) { if (ERROR_ACCESS_DENIED == ::GetLastError()) { return SBOX_TEST_DENIED; } else { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } } else { ::CloseHandle(process); return SBOX_TEST_SUCCEEDED; } }
170,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, requester_id_, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); } Commit Message: [MediaStream] Pass request ID parameters in the right order for OpenDevice() Prior to this CL, requester_id and page_request_id parameters were passed in incorrect order from MediaStreamDispatcherHost to MediaStreamManager for the OpenDevice() operation, which could lead to errors. Bug: 948564 Change-Id: Iadcf3fe26adaac50564102138ce212269cf32d62 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1569113 Reviewed-by: Marina Ciocea <marinaciocea@chromium.org> Commit-Queue: Guido Urdaneta <guidou@chromium.org> Cr-Commit-Position: refs/heads/master@{#651255} CWE ID: CWE-119
void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, requester_id_, page_request_id, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); }
173,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Microtask::performCheckpoint() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); V8PerIsolateData* isolateData = V8PerIsolateData::from(isolate); ASSERT(isolateData); if (isolateData->recursionLevel() || isolateData->performingMicrotaskCheckpoint() || isolateData->destructionPending() || ScriptForbiddenScope::isScriptForbidden()) return; isolateData->setPerformingMicrotaskCheckpoint(true); { V8RecursionScope recursionScope(isolate); isolate->RunMicrotasks(); } isolateData->setPerformingMicrotaskCheckpoint(false); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 R=haraken@chromium.org 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
void Microtask::performCheckpoint() void Microtask::performCheckpoint(v8::Isolate* isolate) { V8PerIsolateData* isolateData = V8PerIsolateData::from(isolate); ASSERT(isolateData); if (isolateData->recursionLevel() || isolateData->performingMicrotaskCheckpoint() || isolateData->destructionPending() || ScriptForbiddenScope::isScriptForbidden()) return; isolateData->setPerformingMicrotaskCheckpoint(true); { V8RecursionScope recursionScope(isolate); isolate->RunMicrotasks(); } isolateData->setPerformingMicrotaskCheckpoint(false); }
171,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int ne2000_buffer_full(NE2000State *s) { int avail, index, boundary; index = s->curpag << 8; boundary = s->boundary << 8; if (index < boundary) return 1; return 0; } Commit Message: CWE ID: CWE-20
static int ne2000_buffer_full(NE2000State *s) { int avail, index, boundary; if (s->stop <= s->start) { return 1; } index = s->curpag << 8; boundary = s->boundary << 8; if (index < boundary) return 1; return 0; }
165,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); REQUEST_SIZE_MATCH(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; }
165,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) { if (!GetTabEntry(contents->web_contents())) { return; } scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue( ExtensionTabUtil::GetTabId(contents->web_contents()))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents()))); object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue( index)); args->Append(object_args); DispatchEvent(contents->profile(), events::kOnTabDetached, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); } 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
void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) { void BrowserEventRouter::TabDetachedAt(WebContents* contents, int index) { if (!GetTabEntry(contents)) { return; } scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue(ExtensionTabUtil::GetTabId(contents))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue( index)); args->Append(object_args); Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); DispatchEvent(profile, events::kOnTabDetached, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); }
171,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: alloc_limit_failure (char *fn_name, size_t size) { fprintf (stderr, "%s: Maximum allocation size exceeded " "(maxsize = %lu; size = %lu).\n", fn_name, (unsigned long)alloc_limit, (unsigned long)size); } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
alloc_limit_failure (char *fn_name, size_t size) { fprintf (stderr, "%s: Maximum allocation size exceeded " "(maxsize = %lu; size = %lu).\n", fn_name, (unsigned long)alloc_limit, (unsigned long)size); }
168,355
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ExtensionTtsController::IsSpeaking() const { return current_utterance_ != NULL; } 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
bool ExtensionTtsController::IsSpeaking() const {
170,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to pair device: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; UnregisterAgent(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to pair device: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; pairing_context_.reset(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); }
171,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); } 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
void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (TEMP_FAILURE_RETRY(send(client_socket_, data, length, 0)) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); }
173,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; }
173,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long Block::GetDiscardPadding() const { return m_discard_padding; } 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
long long Block::GetDiscardPadding() const
174,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ResourceCoordinatorService::OnStart() { ref_factory_.reset(new service_manager::ServiceContextRefFactory( base::Bind(&service_manager::ServiceContext::RequestQuit, base::Unretained(context())))); ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector()); registry_.AddInterface( base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface, base::Unretained(&introspector_))); auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); registry_.AddInterface( base::Bind(&PageSignalGeneratorImpl::BindToInterface, base::Unretained(page_signal_generator_impl.get()))); coordination_unit_manager_.RegisterObserver( std::move(page_signal_generator_impl)); coordination_unit_manager_.RegisterObserver( std::make_unique<MetricsCollector>()); coordination_unit_manager_.RegisterObserver( std::make_unique<IPCVolumeReporter>( std::make_unique<base::OneShotTimer>())); coordination_unit_manager_.OnStart(&registry_, ref_factory_.get()); coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get()); memory_instrumentation_coordinator_ = std::make_unique<memory_instrumentation::CoordinatorImpl>( context()->connector()); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>(); registry_.AddInterface( base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest, base::Unretained(tracing_agent_registry_.get()))); tracing_coordinator_ = std::make_unique<tracing::Coordinator>(); registry_.AddInterface( base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest, base::Unretained(tracing_coordinator_.get()))); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void ResourceCoordinatorService::OnStart() { ref_factory_.reset(new service_manager::ServiceContextRefFactory( base::Bind(&service_manager::ServiceContext::RequestQuit, base::Unretained(context())))); ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector()); registry_.AddInterface( base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface, base::Unretained(&introspector_))); auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); registry_.AddInterface( base::Bind(&PageSignalGeneratorImpl::BindToInterface, base::Unretained(page_signal_generator_impl.get()))); coordination_unit_manager_.RegisterObserver( std::move(page_signal_generator_impl)); coordination_unit_manager_.RegisterObserver( std::make_unique<MetricsCollector>()); coordination_unit_manager_.RegisterObserver( std::make_unique<IPCVolumeReporter>( std::make_unique<base::OneShotTimer>())); coordination_unit_manager_.OnStart(&registry_, ref_factory_.get()); coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get()); memory_instrumentation_coordinator_ = std::make_unique<memory_instrumentation::CoordinatorImpl>( context()->connector()); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindHeapProfilerHelperRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>(); registry_.AddInterface( base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest, base::Unretained(tracing_agent_registry_.get()))); tracing_coordinator_ = std::make_unique<tracing::Coordinator>(); registry_.AddInterface( base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest, base::Unretained(tracing_coordinator_.get()))); }
172,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline quint32 swapBgrToRgb(quint32 pixel) { return ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00); } Commit Message: [Qt] Remove an unnecessary masking from swapBgrToRgb() https://bugs.webkit.org/show_bug.cgi?id=103630 Reviewed by Zoltan Herczeg. Get rid of a masking command in swapBgrToRgb() to speed up a little bit. * platform/graphics/qt/GraphicsContext3DQt.cpp: (WebCore::swapBgrToRgb): git-svn-id: svn://svn.chromium.org/blink/trunk@136375 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
static inline quint32 swapBgrToRgb(quint32 pixel) { return (((pixel << 16) | (pixel >> 16)) & 0x00ff00ff) | (pixel & 0xff00ff00); }
170,963
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); 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
DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(IPPROTO_ICMP, 1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; }
168,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; } Commit Message: Fix always true condition (Thomas Jarosch) CWE ID: CWE-119
do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; }
167,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection, const HandwritingStroke& stroke) { g_return_if_fail(connection); connection->SendHandwritingStroke(stroke); } 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
void ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection, virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { } virtual void CancelHandwriting(int n_strokes) { } }; IBusController* IBusController::Create() { #if defined(HAVE_IBUS) return IBusControllerImpl::GetInstance(); #else return new IBusControllerStubImpl; #endif }
170,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: untrusted_launcher_response_callback (GtkDialog *dialog, int response_id, ActivateParametersDesktop *parameters) { GdkScreen *screen; char *uri; GFile *file; switch (response_id) { case RESPONSE_RUN: { screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); uri = nautilus_file_get_uri (parameters->file); DEBUG ("Launching untrusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); } break; case RESPONSE_MARK_TRUSTED: { file = nautilus_file_get_location (parameters->file); nautilus_file_mark_desktop_file_trusted (file, parameters->parent_window, TRUE, NULL, NULL); g_object_unref (file); } break; default: { /* Just destroy dialog */ } break; } gtk_widget_destroy (GTK_WIDGET (dialog)); activate_parameters_desktop_free (parameters); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
untrusted_launcher_response_callback (GtkDialog *dialog, int response_id, ActivateParametersDesktop *parameters) { GdkScreen *screen; char *uri; GFile *file; switch (response_id) { case GTK_RESPONSE_OK: { file = nautilus_file_get_location (parameters->file); /* We need to do this in order to prevent malicious desktop files * with the executable bit already set. * See https://bugzilla.gnome.org/show_bug.cgi?id=777991 */ nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED, NULL, "yes"); nautilus_file_mark_desktop_file_executable (file, parameters->parent_window, TRUE, NULL, NULL); /* Need to force a reload of the attributes so is_trusted is marked * correctly. Not sure why the general monitor doesn't fire in this * case when setting the metadata */ nautilus_file_invalidate_all_attributes (parameters->file); screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); uri = nautilus_file_get_uri (parameters->file); DEBUG ("Launching untrusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); g_object_unref (file); } break; default: { /* Just destroy dialog */ } break; } gtk_widget_destroy (GTK_WIDGET (dialog)); activate_parameters_desktop_free (parameters); }
167,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(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
void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(id_); }
170,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitIdentity *ret; guint32 uid; ret = NULL; if (POLKIT_IS_UNIX_PROCESS (subject)) { uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if ((gint) uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } ret = polkit_unix_user_new (uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); } else if (POLKIT_IS_UNIX_SESSION (subject)) { if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); } out: return ret; } if (!tmp_process) goto out; process = tmp_process; } Commit Message: CWE ID: CWE-200
polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, gboolean *result_matches, GError **error) { PolkitIdentity *ret; gboolean matches; ret = NULL; matches = FALSE; if (POLKIT_IS_UNIX_PROCESS (subject)) { gint subject_uid, current_uid; GError *local_error; subject_uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if (subject_uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } local_error = NULL; current_uid = polkit_unix_process_get_racy_uid__ (POLKIT_UNIX_PROCESS (subject), &local_error); if (local_error != NULL) { g_propagate_error (error, local_error); goto out; } ret = polkit_unix_user_new (subject_uid); matches = (subject_uid == current_uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); matches = TRUE; } else if (POLKIT_IS_UNIX_SESSION (subject)) { uid_t uid; if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); matches = TRUE; } out: if (result_matches != NULL) { *result_matches = matches; } return ret; } if (!tmp_process) goto out; process = tmp_process; }
165,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; } 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
const char* Track::GetCodecNameAsUTF8() const
174,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen) { return crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen); } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,
167,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) { assert(pCluster); assert(pCluster->m_index < 0); assert(idx >= m_clusterCount); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); if (count >= size) { const long n = (size <= 0) ? 2048 : 2*size; Cluster** const qq = new Cluster*[n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } assert(m_clusters); Cluster** const p = m_clusters + idx; Cluster** q = m_clusters + count; assert(q >= p); assert(q < (m_clusters + size)); while (q > p) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; } m_clusters[idx] = pCluster; ++m_clusterPreloadCount; } 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
void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) if (m_clusterPreloadCount > 0) { assert(m_clusters); Cluster** const p = m_clusters + m_clusterCount; assert(*p); assert((*p)->m_index < 0); Cluster** q = p + m_clusterPreloadCount; assert(q < (m_clusters + size)); for (;;) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; }
174,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; qboolean isLocalConfig; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG); for(search = fs_searchpaths; search; search = search->next) { // autoexec.cfg and wolfconfig.cfg can only be loaded outside of pk3 files. if (isLocalConfig && search->pack) continue; len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } }
170,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GraphicsContext::clip(const Path& path) { #ifdef __WXMAC__ if (paintingDisabled()) return; wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); CGContextRef context = (CGContextRef)gc->GetNativeContext(); if (!context) return; CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath(); if (path.isEmpty()) CGContextClipToRect(context, CGRectZero); else if (nativePath) { CGContextBeginPath(context); CGContextAddPath(context, nativePath); CGContextClip(context); } #else notImplemented(); #endif } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clip(const Path& path) { if (paintingDisabled()) return; // if the path is empty, we clip against a zero rect to reduce the clipping region to // nothing - which is the intended behavior of clip() if the path is empty. if (path.isEmpty()) m_data->context->SetClippingRegion(0, 0, 0, 0); else clipPath(path, RULE_NONZERO); }
170,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
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)) { 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; pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); umount_mnt(p); } change_mnt_propagation(p, MS_PRIVATE); } } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> CWE ID: CWE-284
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); } }
167,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void OMXNodeInstance::onEvent( OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) { const char *arg1String = "??"; const char *arg2String = "??"; ADebug::Level level = ADebug::kDebugInternalState; switch (event) { case OMX_EventCmdComplete: arg1String = asString((OMX_COMMANDTYPE)arg1); switch (arg1) { case OMX_CommandStateSet: arg2String = asString((OMX_STATETYPE)arg2); level = ADebug::kDebugState; break; case OMX_CommandFlush: case OMX_CommandPortEnable: { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } default: arg2String = portString(arg2); } break; case OMX_EventError: arg1String = asString((OMX_ERRORTYPE)arg1); level = ADebug::kDebugLifeCycle; break; case OMX_EventPortSettingsChanged: arg2String = asString((OMX_INDEXEXTTYPE)arg2); default: arg1String = portString(arg1); } CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)", asString(event), event, arg1String, arg1, arg2String, arg2); const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && event == OMX_EventCmdComplete && arg1 == OMX_CommandStateSet && arg2 == OMX_StateExecuting) { bufferSource->omxExecuting(); } } Commit Message: IOMX: allow configuration after going to loaded state This was disallowed recently but we still use it as MediaCodcec.stop only goes to loaded state, and does not free component. Bug: 31450460 Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d (cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b) CWE ID: CWE-200
void OMXNodeInstance::onEvent( OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) { const char *arg1String = "??"; const char *arg2String = "??"; ADebug::Level level = ADebug::kDebugInternalState; switch (event) { case OMX_EventCmdComplete: arg1String = asString((OMX_COMMANDTYPE)arg1); switch (arg1) { case OMX_CommandStateSet: arg2String = asString((OMX_STATETYPE)arg2); level = ADebug::kDebugState; break; case OMX_CommandFlush: case OMX_CommandPortEnable: { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } default: arg2String = portString(arg2); } break; case OMX_EventError: arg1String = asString((OMX_ERRORTYPE)arg1); level = ADebug::kDebugLifeCycle; break; case OMX_EventPortSettingsChanged: arg2String = asString((OMX_INDEXEXTTYPE)arg2); default: arg1String = portString(arg1); } CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)", asString(event), event, arg1String, arg1, arg2String, arg2); const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && event == OMX_EventCmdComplete && arg1 == OMX_CommandStateSet && arg2 == OMX_StateExecuting) { bufferSource->omxExecuting(); } // allow configuration if we return to the loaded state if (event == OMX_EventCmdComplete && arg1 == OMX_CommandStateSet && arg2 == OMX_StateLoaded) { mSailed = false; } }
173,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_MINIT_FUNCTION(xml) { le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number); REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT); /* this object should not be pre-initialised at compile time, as the order of members may vary */ php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper; php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper; php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper; #ifdef LIBXML_EXPAT_COMPAT REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT); #else REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; } Commit Message: CWE ID: CWE-119
PHP_MINIT_FUNCTION(xml) { le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number); REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT); /* this object should not be pre-initialised at compile time, as the order of members may vary */ php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper; php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper; php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper; #ifdef LIBXML_EXPAT_COMPAT REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT); #else REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; }
165,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Browser::SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) { int index = tab_strip_model_->GetIndexOfWebContents(web_contents); if (index == TabStripModel::kNoTab) { return; } tab_strip_model_->SetTabBlocked(index, blocked); bool browser_active = BrowserList::GetInstance()->GetLastActive() == this; bool contents_is_active = tab_strip_model_->GetActiveWebContents() == web_contents; if (!blocked && contents_is_active && browser_active) web_contents->Focus(); } Commit Message: If a dialog is shown, drop fullscreen. BUG=875066, 817809, 792876, 812769, 813815 TEST=included Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db Reviewed-on: https://chromium-review.googlesource.com/1185208 Reviewed-by: Sidney San Martín <sdy@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#586418} CWE ID: CWE-20
void Browser::SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) { int index = tab_strip_model_->GetIndexOfWebContents(web_contents); if (index == TabStripModel::kNoTab) { return; } // For security, if the WebContents is in fullscreen, have it drop fullscreen. // This gives the user the context they need in order to make informed // decisions. if (web_contents->IsFullscreenForCurrentTab()) web_contents->ExitFullscreen(true); tab_strip_model_->SetTabBlocked(index, blocked); bool browser_active = BrowserList::GetInstance()->GetLastActive() == this; bool contents_is_active = tab_strip_model_->GetActiveWebContents() == web_contents; if (!blocked && contents_is_active && browser_active) web_contents->Focus(); }
172,664
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void SVGDocumentExtensions::startAnimations() { WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> > timeContainers; timeContainers.appendRange(m_timeContainers.begin(), m_timeContainers.end()); WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator end = timeContainers.end(); for (WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator itr = timeContainers.begin(); itr != end; ++itr) (*itr)->timeContainer()->begin(); } Commit Message: SVG: Moving animating <svg> to other iframe should not crash. Moving SVGSVGElement with its SMILTimeContainer already started caused crash before this patch. |SVGDocumentExtentions::startAnimations()| calls begin() against all SMILTimeContainers in the document, but the SMILTimeContainer for <svg> moved from other document may be already started. BUG=369860 Review URL: https://codereview.chromium.org/290353002 git-svn-id: svn://svn.chromium.org/blink/trunk@174338 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void SVGDocumentExtensions::startAnimations() { WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> > timeContainers; timeContainers.appendRange(m_timeContainers.begin(), m_timeContainers.end()); WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator end = timeContainers.end(); for (WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator itr = timeContainers.begin(); itr != end; ++itr) { SMILTimeContainer* timeContainer = (*itr)->timeContainer(); if (!timeContainer->isStarted()) timeContainer->begin(); } }
171,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_set_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) { png_debug1(1, "in %s storage function", "IHDR"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->width = width; info_ptr->height = height; info_ptr->bit_depth = (png_byte)bit_depth; info_ptr->color_type = (png_byte)color_type; info_ptr->compression_type = (png_byte)compression_type; info_ptr->filter_type = (png_byte)filter_type; info_ptr->interlace_type = (png_byte)interlace_type; png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, info_ptr->compression_type, info_ptr->filter_type); if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); /* Check for potential overflow */ if (width > (PNG_UINT_32_MAX >> 3) /* 8-byte RGBA pixels */ - 64 /* bigrowbuf hack */ - 1 /* filter byte */ - 7*8 /* rounding of width to multiple of 8 pixels */ - 8) /* extra max_pixel_depth pad */ info_ptr->rowbytes = (png_size_t)0; else info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) { png_debug1(1, "in %s storage function", "IHDR"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->width = width; info_ptr->height = height; info_ptr->bit_depth = (png_byte)bit_depth; info_ptr->color_type = (png_byte)color_type; info_ptr->compression_type = (png_byte)compression_type; info_ptr->filter_type = (png_byte)filter_type; info_ptr->interlace_type = (png_byte)interlace_type; png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, info_ptr->compression_type, info_ptr->filter_type); if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); /* Check for potential overflow */ if (width > (PNG_UINT_32_MAX >> 3) /* 8-byte RGBA pixels */ - 64 /* bigrowbuf hack */ - 1 /* filter byte */ - 7*8 /* rounding of width to multiple of 8 pixels */ - 8) /* extra max_pixel_depth pad */ { info_ptr->rowbytes = (png_size_t)0; png_error(png_ptr, "Image width is too large for this architecture"); } else info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); }
172,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const UsbDeviceHandle::TransferCallback& callback() const { return callback_; } Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <rockot@chromium.org> Commit-Queue: Taiju Tsuiki <tzik@chromium.org> Cr-Commit-Position: refs/heads/master@{#478549} CWE ID:
const UsbDeviceHandle::TransferCallback& callback() const { UsbDeviceHandle::TransferCallback GetCallback() { return base::Bind(&TestCompletionCallback::SetResult, base::Unretained(this)); }
171,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; } 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
SegmentInfo::~SegmentInfo()
174,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nlmsvc_grant_reply(struct nlm_cookie *cookie, __be32 status) { struct nlm_block *block; dprintk("grant_reply: looking for cookie %x, s=%d \n", *(unsigned int *)(cookie->data), status); if (!(block = nlmsvc_find_block(cookie))) return; if (block) { if (status == nlm_lck_denied_grace_period) { /* Try again in a couple of seconds */ nlmsvc_insert_block(block, 10 * HZ); } else { /* Lock is now held by client, or has been rejected. * In both cases, the block should be removed. */ nlmsvc_unlink_block(block); } } nlmsvc_release_block(block); } 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
nlmsvc_grant_reply(struct nlm_cookie *cookie, __be32 status) { struct nlm_block *block; dprintk("grant_reply: looking for cookie %x, s=%d \n", *(unsigned int *)(cookie->data), status); if (!(block = nlmsvc_find_block(cookie))) return; if (status == nlm_lck_denied_grace_period) { /* Try again in a couple of seconds */ nlmsvc_insert_block(block, 10 * HZ); } else { /* * Lock is now held by client, or has been rejected. * In both cases, the block should be removed. */ nlmsvc_unlink_block(block); } nlmsvc_release_block(block); }
168,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit, const ContentSecurityPolicy* previous_document_csp) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else { if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); } } if (!policy_to_inherit) policy_to_inherit = previous_document_csp; if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void Document::InitContentSecurityPolicy( void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp, const Document* origin_document) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); ContentSecurityPolicy* policy_to_inherit = nullptr; if (origin_document) policy_to_inherit = origin_document->GetContentSecurityPolicy(); // We should inherit the navigation initiator CSP if the document is loaded // using a local-scheme url. if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (IsPluginDocument()) { // TODO(andypaicu): This should inherit the origin document's plugin types // but because this could be a OOPIF document it might not have access. // In this situation we fallback on using the parent/opener. if (origin_document) { GetContentSecurityPolicy()->CopyPluginTypesFrom( origin_document->GetContentSecurityPolicy()); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); GetContentSecurityPolicy()->CopyPluginTypesFrom( inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); } } } }
173,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) return false; if(buffer[len-1] != '\0') SLOGW("String is not zero-terminated"); int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ dispatchCommand(c, buffer + offset); offset = i + 1; } } return true; } Commit Message: Fix vold vulnerability in FrameworkListener Modify FrameworkListener to ignore commands that exceed the maximum buffer length and send an error message. Bug: 29831647 Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950 Signed-off-by: Connor O'Brien <connoro@google.com> (cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a) (cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e) CWE ID: CWE-264
bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) { return false; } else if (buffer[len-1] != '\0') { SLOGW("String is not zero-terminated"); android_errorWriteLog(0x534e4554, "29831647"); c->sendMsg(500, "Command too large for buffer", false); mSkipToNextNullByte = true; return false; } int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ if (mSkipToNextNullByte) { mSkipToNextNullByte = false; } else { dispatchCommand(c, buffer + offset); } offset = i + 1; } } mSkipToNextNullByte = false; return true; }
173,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void usage_exit() { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n", exec_name); exit(EXIT_FAILURE); } 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
void usage_exit() { void usage_exit(void) { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n", exec_name); exit(EXIT_FAILURE); }
174,486
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: hb_buffer_ensure_separate (hb_buffer_t *buffer, unsigned int size) { hb_buffer_ensure (buffer, size); if (buffer->out_info == buffer->info) { assert (buffer->have_output); if (!buffer->pos) buffer->pos = (hb_internal_glyph_position_t *) calloc (buffer->allocated, sizeof (buffer->pos[0])); buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos; memcpy (buffer->out_info, buffer->info, buffer->out_len * sizeof (buffer->out_info[0])); } } Commit Message: CWE ID:
hb_buffer_ensure_separate (hb_buffer_t *buffer, unsigned int size) { if (unlikely (!hb_buffer_ensure (buffer, size))) return FALSE; if (buffer->out_info == buffer->info) { assert (buffer->have_output); buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos; memcpy (buffer->out_info, buffer->info, buffer->out_len * sizeof (buffer->out_info[0])); } return TRUE; }
164,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = iw_get_ui32_e(&d[4],e.endian); iwjpeg_scan_exif_ifd(rctx,&e,ifd); } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = get_exif_ui32(&e, 4); iwjpeg_scan_exif_ifd(rctx,&e,ifd); }
168,115
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
17