instruction
stringclasses
1 value
input
stringlengths
90
5.47k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) { ASSERT(header->checkHeader()); if (header->payloadSize() >= newSize) return true; size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { m_currentAllocationPoint += expandSize; ASSERT(m_remainingAllocationSize >= expandSize); setRemainingAllocationSize(m_remainingAllocationSize - expandSize); SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize); header->setSize(allocationSize); ASSERT(findPageFromAddress(header->payloadEnd() - 1)); return true; } return false; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) { header->checkHeader(); if (header->payloadSize() >= newSize) return true; size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { m_currentAllocationPoint += expandSize; ASSERT(m_remainingAllocationSize >= expandSize); setRemainingAllocationSize(m_remainingAllocationSize - expandSize); SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize); header->setSize(allocationSize); ASSERT(findPageFromAddress(header->payloadEnd() - 1)); return true; } return false; }
172,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) transliterator_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; ustr_skeleton.toUTF8String(skeleton); return LookupMatchInTopDomains(skeleton); } Commit Message: Add a few more confusable map entries 1. Map Malaylam U+0D1F to 's'. 2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase letters. The characters in new confusable map entries are replaced by their Latin "look-alike" characters before the skeleton is calculated to compare with top domain names. Bug: 784761,773930 Test: components_unittests --gtest_filter=*IDNToUni* Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee Reviewed-on: https://chromium-review.googlesource.com/805214 Reviewed-by: Peter Kasting <pkasting@chromium.org> Commit-Queue: Jungshik Shin <jshin@chromium.org> Cr-Commit-Position: refs/heads/master@{#521648} CWE ID: CWE-20
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) diacritic_remover_.get()->transliterate(ustr_host); extra_confusable_mapper_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton)); }
172,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char32_t *cur_utf32 = src; const char32_t *end_utf32 = src + src_len; char *cur = dst; while (cur_utf32 < end_utf32) { size_t len = utf32_codepoint_utf8_length(*cur_utf32); utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst) void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char32_t *cur_utf32 = src; const char32_t *end_utf32 = src + src_len; char *cur = dst; while (cur_utf32 < end_utf32) { size_t len = utf32_codepoint_utf8_length(*cur_utf32); LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len); utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len); cur += len; dst_len -= len; } LOG_ALWAYS_FATAL_IF(dst_len < 1, "dst_len < 1: %zu < 1", dst_len); *cur = '\0'; }
173,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl2_generate_key_material(SSL *s) { unsigned int i; EVP_MD_CTX ctx; unsigned char *km; unsigned char c = '0'; const EVP_MD *md5; int md_size; md5 = EVP_md5(); # ifdef CHARSET_EBCDIC c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see * SSLv2 docu */ # endif EVP_MD_CTX_init(&ctx); km = s->s2->key_material; if (s->session->master_key_length < 0 || s->session->master_key_length > (int)sizeof(s->session->master_key)) { SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } md_size = EVP_MD_size(md5); if (md_size < 0) return 0; for (i = 0; i < s->s2->key_material_length; i += md_size) { if (((km - s->s2->key_material) + md_size) > (int)sizeof(s->s2->key_material)) { /* * EVP_DigestFinal_ex() below would write beyond buffer */ SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } EVP_DigestInit_ex(&ctx, md5, NULL); OPENSSL_assert(s->session->master_key_length >= 0 && s->session->master_key_length < (int)sizeof(s->session->master_key)); EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, &c, 1); c++; EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length); EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length); EVP_DigestFinal_ex(&ctx, km, NULL); km += md_size; } EVP_MD_CTX_cleanup(&ctx); return 1; } Commit Message: CWE ID: CWE-20
int ssl2_generate_key_material(SSL *s) { unsigned int i; EVP_MD_CTX ctx; unsigned char *km; unsigned char c = '0'; const EVP_MD *md5; int md_size; md5 = EVP_md5(); # ifdef CHARSET_EBCDIC c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see * SSLv2 docu */ # endif EVP_MD_CTX_init(&ctx); km = s->s2->key_material; if (s->session->master_key_length < 0 || s->session->master_key_length > (int)sizeof(s->session->master_key)) { SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } md_size = EVP_MD_size(md5); if (md_size < 0) return 0; for (i = 0; i < s->s2->key_material_length; i += md_size) { if (((km - s->s2->key_material) + md_size) > (int)sizeof(s->s2->key_material)) { /* * EVP_DigestFinal_ex() below would write beyond buffer */ SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } EVP_DigestInit_ex(&ctx, md5, NULL); OPENSSL_assert(s->session->master_key_length >= 0 && s->session->master_key_length <= (int)sizeof(s->session->master_key)); EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, &c, 1); c++; EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length); EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length); EVP_DigestFinal_ex(&ctx, km, NULL); km += md_size; } EVP_MD_CTX_cleanup(&ctx); return 1; }
164,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void filter_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { const int kInterp_Extend = 4; const unsigned int intermediate_height = (kInterp_Extend - 1) + output_height + kInterp_Extend; /* Size of intermediate_buffer is max_intermediate_height * filter_max_width, * where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height * + kInterp_Extend * = 3 + 16 + 4 * = 23 * and filter_max_width = 16 */ uint8_t intermediate_buffer[71 * 64]; const int intermediate_next_stride = 1 - intermediate_height * output_width; { uint8_t *output_ptr = intermediate_buffer; const int src_next_row_stride = src_stride - output_width; unsigned int i, j; src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1); for (i = 0; i < intermediate_height; ++i) { for (j = 0; j < output_width; ++j) { const int temp = (src_ptr[0] * HFilter[0]) + (src_ptr[1] * HFilter[1]) + (src_ptr[2] * HFilter[2]) + (src_ptr[3] * HFilter[3]) + (src_ptr[4] * HFilter[4]) + (src_ptr[5] * HFilter[5]) + (src_ptr[6] * HFilter[6]) + (src_ptr[7] * HFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding *output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT); ++src_ptr; output_ptr += intermediate_height; } src_ptr += src_next_row_stride; output_ptr += intermediate_next_stride; } } { uint8_t *src_ptr = intermediate_buffer; const int dst_next_row_stride = dst_stride - output_width; unsigned int i, j; for (i = 0; i < output_height; ++i) { for (j = 0; j < output_width; ++j) { const int temp = (src_ptr[0] * VFilter[0]) + (src_ptr[1] * VFilter[1]) + (src_ptr[2] * VFilter[2]) + (src_ptr[3] * VFilter[3]) + (src_ptr[4] * VFilter[4]) + (src_ptr[5] * VFilter[5]) + (src_ptr[6] * VFilter[6]) + (src_ptr[7] * VFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding *dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT); src_ptr += intermediate_height; } src_ptr += intermediate_next_stride; dst_ptr += dst_next_row_stride; } } } 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 filter_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { const int kInterp_Extend = 4; const unsigned int intermediate_height = (kInterp_Extend - 1) + output_height + kInterp_Extend; unsigned int i, j; // Size of intermediate_buffer is max_intermediate_height * filter_max_width, // where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height // + kInterp_Extend // = 3 + 16 + 4 // = 23 // and filter_max_width = 16 // uint8_t intermediate_buffer[71 * kMaxDimension]; const int intermediate_next_stride = 1 - intermediate_height * output_width; uint8_t *output_ptr = intermediate_buffer; const int src_next_row_stride = src_stride - output_width; src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1); for (i = 0; i < intermediate_height; ++i) { for (j = 0; j < output_width; ++j) { // Apply filter... const int temp = (src_ptr[0] * HFilter[0]) + (src_ptr[1] * HFilter[1]) + (src_ptr[2] * HFilter[2]) + (src_ptr[3] * HFilter[3]) + (src_ptr[4] * HFilter[4]) + (src_ptr[5] * HFilter[5]) + (src_ptr[6] * HFilter[6]) + (src_ptr[7] * HFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding // Normalize back to 0-255... *output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT); ++src_ptr; output_ptr += intermediate_height; } src_ptr += src_next_row_stride; output_ptr += intermediate_next_stride; } src_ptr = intermediate_buffer; const int dst_next_row_stride = dst_stride - output_width; for (i = 0; i < output_height; ++i) { for (j = 0; j < output_width; ++j) { // Apply filter... const int temp = (src_ptr[0] * VFilter[0]) + (src_ptr[1] * VFilter[1]) + (src_ptr[2] * VFilter[2]) + (src_ptr[3] * VFilter[3]) + (src_ptr[4] * VFilter[4]) + (src_ptr[5] * VFilter[5]) + (src_ptr[6] * VFilter[6]) + (src_ptr[7] * VFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding // Normalize back to 0-255... *dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT); src_ptr += intermediate_height; } src_ptr += intermediate_next_stride; dst_ptr += dst_next_row_stride; } }
174,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } Commit Message: smart_pkt: verify packet length exceeds PKT_LEN_SIZE Each packet line in the Git protocol is prefixed by a four-byte length of how much data will follow, which we parse in `git_pkt_parse_line`. The transmitted length can either be equal to zero in case of a flush packet or has to be at least of length four, as it also includes the encoded length itself. Not checking this may result in a buffer overflow as we directly pass the length to functions which accept a `size_t` length as parameter. Fix the issue by verifying that non-flush packets have at least a length of `PKT_LEN_SIZE`. CWE ID: CWE-119
int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; /* * The length has to be exactly 0 in case of a flush * packet or greater than PKT_LEN_SIZE, as the decoded * length includes its own encoded length of four bytes. */ if (len != 0 && len < PKT_LEN_SIZE) return GIT_ERROR; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; }
168,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); } Commit Message: (for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check In lmp_print_data_link_subobjs(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; }
169,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DownloadManagerImpl::InterceptDownload( const download::DownloadCreateInfo& info) { WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID( info.render_process_id, info.render_frame_id); if (info.is_new_download && info.result == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) { if (web_contents) { std::vector<GURL> url_chain(info.url_chain); GURL url = url_chain.back(); url_chain.pop_back(); NavigationController::LoadURLParams params(url); params.has_user_gesture = info.has_user_gesture; params.referrer = Referrer( info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } if (!delegate_ || !delegate_->InterceptDownloadIfApplicable( info.url(), info.mime_type, info.request_origin, web_contents)) { return false; } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } 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
bool DownloadManagerImpl::InterceptDownload( const download::DownloadCreateInfo& info) { WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID( info.render_process_id, info.render_frame_id); if (info.is_new_download && info.result == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) { if (web_contents) { std::vector<GURL> url_chain(info.url_chain); GURL url = url_chain.back(); url_chain.pop_back(); NavigationController::LoadURLParams params(url); params.has_user_gesture = info.has_user_gesture; params.referrer = Referrer( info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; params.frame_tree_node_id = RenderFrameHost::GetFrameTreeNodeIdForRoutingId( info.render_process_id, info.render_frame_id); web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } if (!delegate_ || !delegate_->InterceptDownloadIfApplicable( info.url(), info.mime_type, info.request_origin, web_contents)) { return false; } if (info.request_handle) info.request_handle->CancelRequest(false); return true; }
173,023
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } } 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
static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; }
174,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; } Commit Message: Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch CWE ID: CWE-119
static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { if (i >= MAX_CHANNELS - num_excl_chan - 7) return n; for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; }
169,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable( const NTPTilesVector& tiles) { JNIEnv* env = AttachCurrentThread(); std::vector<base::string16> titles; std::vector<std::string> urls; std::vector<std::string> whitelist_icon_paths; std::vector<int> sources; titles.reserve(tiles.size()); urls.reserve(tiles.size()); whitelist_icon_paths.reserve(tiles.size()); sources.reserve(tiles.size()); for (const auto& tile : tiles) { titles.emplace_back(tile.title); urls.emplace_back(tile.url.spec()); whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value()); sources.emplace_back(static_cast<int>(tile.source)); } Java_MostVisitedURLsObserver_onMostVisitedURLsAvailable( env, observer_, ToJavaArrayOfStrings(env, titles), ToJavaArrayOfStrings(env, urls), ToJavaArrayOfStrings(env, whitelist_icon_paths), ToJavaIntArray(env, sources)); } Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer. BUG=677672 Review-Url: https://codereview.chromium.org/2697543002 Cr-Commit-Position: refs/heads/master@{#449958} CWE ID: CWE-17
void MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable( const NTPTilesVector& tiles) { JNIEnv* env = AttachCurrentThread(); std::vector<base::string16> titles; std::vector<std::string> urls; std::vector<std::string> whitelist_icon_paths; std::vector<int> sources; titles.reserve(tiles.size()); urls.reserve(tiles.size()); whitelist_icon_paths.reserve(tiles.size()); sources.reserve(tiles.size()); for (const auto& tile : tiles) { titles.emplace_back(tile.title); urls.emplace_back(tile.url.spec()); whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value()); sources.emplace_back(static_cast<int>(tile.source)); } Java_Observer_onMostVisitedURLsAvailable( env, observer_, ToJavaArrayOfStrings(env, titles), ToJavaArrayOfStrings(env, urls), ToJavaArrayOfStrings(env, whitelist_icon_paths), ToJavaIntArray(env, sources)); }
172,035
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS")); t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS")); t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*)); if (t->Data == NULL) { SynError(it8, "AllocateDataSet: Unable to allocate data array"); } } Commit Message: Upgrade Visual studio 2017 15.8 - Upgrade to 15.8 - Add check on CGATS memory allocation (thanks to Quang Nguyen for pointing out this) CWE ID: CWE-190
void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS")); t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS")); if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe) { SynError(it8, "AllocateDataSet: too much data"); } else { t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*)); if (t->Data == NULL) { SynError(it8, "AllocateDataSet: Unable to allocate data array"); } } }
169,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::WasHidden() { if (host_->is_hidden()) return; host_->WasHidden(); released_front_lock_ = NULL; if (ShouldReleaseFrontSurface() && host_->is_accelerated_compositing_active()) { current_surface_ = 0; UpdateExternalTexture(); } AdjustSurfaceProtection(); #if defined(OS_WIN) aura::RootWindow* root_window = window_->GetRootWindow(); if (root_window) { HWND parent = root_window->GetAcceleratedWidget(); LPARAM lparam = reinterpret_cast<LPARAM>(this); EnumChildWindows(parent, HideWindowsCallback, lparam); } #endif } 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 RenderWidgetHostViewAura::WasHidden() { if (host_->is_hidden()) return; host_->WasHidden(); released_front_lock_ = NULL; #if defined(OS_WIN) aura::RootWindow* root_window = window_->GetRootWindow(); if (root_window) { HWND parent = root_window->GetAcceleratedWidget(); LPARAM lparam = reinterpret_cast<LPARAM>(this); EnumChildWindows(parent, HideWindowsCallback, lparam); } #endif }
171,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void SetUp() { old_client_ = content::GetContentClient(); content::SetContentClient(&client_); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); }
171,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { int scriptId = function->ScriptId(); if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound) return v8::Null(m_isolate); v8::Local<v8::Object> location = v8::Object::New(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!markAsInternal(context, location, V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { int scriptId = function->ScriptId(); if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound) return v8::Null(m_isolate); v8::Local<v8::Object> location = v8::Object::New(m_isolate); if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!markAsInternal(context, location, V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; }
172,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { memmove(s+j, s+qs, blen - qs); j += blen - qs; } buffer_string_set_length(b, j); return qs; } Commit Message: [core] fix abort in http-parseopts (fixes #2945) fix abort in server.http-parseopts with url-path-2f-decode enabled (thx stze) x-ref: "Security - SIGABRT during GET request handling with url-path-2f-decode enabled" https://redmine.lighttpd.net/issues/2945 CWE ID: CWE-190
static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { const int qslen = blen - qs; memmove(s+j, s+qs, (size_t)qslen); qs = j; j += qslen; } buffer_string_set_length(b, j); return qs; }
169,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioSource::AudioSource( audio_source_t inputSource, const String16 &opPackageName, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate) : mStarted(false), mSampleRate(sampleRate), mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate), mPrevSampleTimeUs(0), mFirstSampleTimeUs(-1ll), mNumFramesReceived(0), mNumClientOwnedBuffers(0) { ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u", sampleRate, outSampleRate, channelCount); CHECK(channelCount == 1 || channelCount == 2); CHECK(sampleRate > 0); size_t minFrameCount; status_t status = AudioRecord::getMinFrameCount(&minFrameCount, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount)); if (status == OK) { uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount; size_t bufCount = 2; while ((bufCount * frameCount) < minFrameCount) { bufCount++; } mRecord = new AudioRecord( inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), opPackageName, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, frameCount /*notificationFrames*/); mInitCheck = mRecord->initCheck(); if (mInitCheck != OK) { mRecord.clear(); } } else { mInitCheck = status; } } Commit Message: AudioSource: initialize variables to prevent info leak Bug: 27855172 Change-Id: I3d33e0a9cc5cf8a758d7b0794590b09c43a24561 CWE ID: CWE-200
AudioSource::AudioSource( audio_source_t inputSource, const String16 &opPackageName, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate) : mStarted(false), mSampleRate(sampleRate), mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate), mTrackMaxAmplitude(false), mStartTimeUs(0), mMaxAmplitude(0), mPrevSampleTimeUs(0), mFirstSampleTimeUs(-1ll), mInitialReadTimeUs(0), mNumFramesReceived(0), mNumClientOwnedBuffers(0) { ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u", sampleRate, outSampleRate, channelCount); CHECK(channelCount == 1 || channelCount == 2); CHECK(sampleRate > 0); size_t minFrameCount; status_t status = AudioRecord::getMinFrameCount(&minFrameCount, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount)); if (status == OK) { uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount; size_t bufCount = 2; while ((bufCount * frameCount) < minFrameCount) { bufCount++; } mRecord = new AudioRecord( inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), opPackageName, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, frameCount /*notificationFrames*/); mInitCheck = mRecord->initCheck(); if (mInitCheck != OK) { mRecord.clear(); } } else { mInitCheck = status; } }
173,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } Commit Message: CWE ID: CWE-20
PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); }
165,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info, PassRefPtr<Uint8Array> imagePixels, size_t imageRowBytes) { SkPixmap pixmap(info, imagePixels->data(), imageRowBytes); return SkImage::MakeFromRaster(pixmap, [](const void*, void* pixels) { static_cast<Uint8Array*>(pixels)->deref(); }, imagePixels.leakRef()); } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info, PassRefPtr<Uint8Array> imagePixels, unsigned imageRowBytes) { SkPixmap pixmap(info, imagePixels->data(), imageRowBytes); return SkImage::MakeFromRaster(pixmap, [](const void*, void* pixels) { static_cast<Uint8Array*>(pixels)->deref(); }, imagePixels.leakRef()); }
172,503
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(xml_parse_into_struct) { xml_parser *parser; zval *pind, **xdata, **info = NULL; char *data; int data_len, ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) { return; } if (info) { zval_dtor(*info); array_init(*info); } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); zval_dtor(*xdata); array_init(*xdata); parser->data = *xdata; if (info) { parser->info = *info; } parser->level = 0; parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0); XML_SetDefaultHandler(parser->parser, _xml_defaultHandler); XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler); XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler); parser->isparsing = 1; ret = XML_Parse(parser->parser, data, data_len, 1); parser->isparsing = 0; RETVAL_LONG(ret); } Commit Message: CWE ID: CWE-119
PHP_FUNCTION(xml_parse_into_struct) { xml_parser *parser; zval *pind, **xdata, **info = NULL; char *data; int data_len, ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) { return; } if (info) { zval_dtor(*info); array_init(*info); } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); zval_dtor(*xdata); array_init(*xdata); parser->data = *xdata; if (info) { parser->info = *info; } parser->level = 0; parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0); XML_SetDefaultHandler(parser->parser, _xml_defaultHandler); XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler); XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler); parser->isparsing = 1; ret = XML_Parse(parser->parser, data, data_len, 1); parser->isparsing = 0; RETVAL_LONG(ret); }
165,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } }
167,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::Destroy(bool also_delete) { DCHECK(!destroyed_); destroyed_ = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this), NotificationService::NoDetails()); if (view_) { view_->Destroy(); view_.reset(); } process_->RemoveRoute(routing_id_); g_routing_id_widget_map.Get().erase( RenderWidgetHostID(process_->GetID(), routing_id_)); if (delegate_) delegate_->RenderWidgetDeleted(this); if (also_delete) delete this; } Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI BUG=590284 Review URL: https://codereview.chromium.org/1747183002 Cr-Commit-Position: refs/heads/master@{#378844} CWE ID:
void RenderWidgetHostImpl::Destroy(bool also_delete) { DCHECK(!destroyed_); destroyed_ = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this), NotificationService::NoDetails()); if (view_) { view_->Destroy(); view_.reset(); } process_->RemoveRoute(routing_id_); g_routing_id_widget_map.Get().erase( RenderWidgetHostID(process_->GetID(), routing_id_)); if (delegate_) delegate_->RenderWidgetDeleted(this); if (also_delete) { CHECK(!owner_delegate_); delete this; } }
172,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) { NavigationEntry* pending_entry = controller_->GetPendingEntry(); bool pending_matches_fail_msg = pending_entry && expected_pending_entry_id == pending_entry->GetUniqueID(); if (!pending_matches_fail_msg) return; bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs(); if (pending_entry != controller_->GetVisibleEntry() || !should_preserve_entry) { controller_->DiscardPendingEntry(true); controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } } Commit Message: Don't preserve NavigationEntry for failed navigations with invalid URLs. The formatting logic may rewrite such URLs into an unsafe state. This is a first step before preventing navigations to invalid URLs entirely. Bug: 850824 Change-Id: I71743bfb4b610d55ce901ee8902125f934a2bb23 Reviewed-on: https://chromium-review.googlesource.com/c/1252942 Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#597304} CWE ID: CWE-20
void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) { NavigationEntry* pending_entry = controller_->GetPendingEntry(); bool pending_matches_fail_msg = pending_entry && expected_pending_entry_id == pending_entry->GetUniqueID(); if (!pending_matches_fail_msg) return; // Do not leave the pending entry visible if it has an invalid URL, since this // might be formatted in an unexpected or unsafe way. // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824. // bool should_preserve_entry = pending_entry->GetURL().is_valid() && (controller_->IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs()); if (pending_entry != controller_->GetVisibleEntry() || !should_preserve_entry) { controller_->DiscardPendingEntry(true); controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } }
172,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SeekHead::~SeekHead() { delete[] m_entries; delete[] m_void_elements; } 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
SeekHead::~SeekHead() SeekHead::~SeekHead() { delete[] m_entries; delete[] m_void_elements; }
174,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); put_io_context(ioc); } } Commit Message: block: Fix io_context leak after clone with CLONE_IO With CLONE_IO, copy_io() increments both ioc->refcount and ioc->nr_tasks. However exit_io_context() only decrements ioc->refcount if ioc->nr_tasks reaches 0. Always call put_io_context() in exit_io_context(). Signed-off-by: Louis Rilling <louis.rilling@kerlabs.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com> CWE ID: CWE-20
void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); }
165,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); }
165,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAVC::drainAllOutputBuffers(bool eos) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); H264SwDecPicture decodedPicture; if (mHeadersDecoded) { while (!outQueue.empty() && H264SWDEC_PIC_RDY == H264SwDecNextPicture( mHandle, &decodedPicture, eos /* flush */)) { int32_t picId = decodedPicture.picId; uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture; drainOneOutputBuffer(picId, data); } } if (!eos) { return; } while (!outQueue.empty()) { BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nTimeStamp = 0; outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mEOSStatus = OUTPUT_FRAMES_FLUSHED; } } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20
void SoftAVC::drainAllOutputBuffers(bool eos) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); H264SwDecPicture decodedPicture; if (mHeadersDecoded) { while (!outQueue.empty() && H264SWDEC_PIC_RDY == H264SwDecNextPicture( mHandle, &decodedPicture, eos /* flush */)) { int32_t picId = decodedPicture.picId; uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture; if (!drainOneOutputBuffer(picId, data)) { ALOGE("Drain failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } } if (!eos) { return; } while (!outQueue.empty()) { BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nTimeStamp = 0; outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mEOSStatus = OUTPUT_FRAMES_FLUSHED; } }
174,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct *desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; desc = get_desc(sel); if (!desc) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc->type & BIT(3))) return -EINVAL; switch ((desc->l << 1) | desc->d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: stable@vger.kernel.org Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; if (!get_desc(&desc, sel)) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc.type & BIT(3))) return -EINVAL; switch ((desc.l << 1) | desc.d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } }
169,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline || h263type->eLevel != OMX_VIDEO_H263Level45 || (h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || h263type->bPLUSPTYPEAllowed != OMX_FALSE || h263type->bForceRoundingTypeToZero != OMX_FALSE || h263type->nPictureHeaderRepetition != 0 || h263type->nGOBHeaderInterval != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore || mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 || (mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || mpeg4type->nBFrames != 0 || mpeg4type->nIDCVLCThreshold != 0 || mpeg4type->bACPred != OMX_TRUE || mpeg4type->nMaxPacketSize != 256 || mpeg4type->nTimeIncRes != 1000 || mpeg4type->nHeaderExtension != 0 || mpeg4type->bReversibleVLC != OMX_FALSE) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (!isValidOMXParam(h263type)) { return OMX_ErrorBadParameter; } if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline || h263type->eLevel != OMX_VIDEO_H263Level45 || (h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || h263type->bPLUSPTYPEAllowed != OMX_FALSE || h263type->bForceRoundingTypeToZero != OMX_FALSE || h263type->nPictureHeaderRepetition != 0 || h263type->nGOBHeaderInterval != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (!isValidOMXParam(mpeg4type)) { return OMX_ErrorBadParameter; } if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore || mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 || (mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || mpeg4type->nBFrames != 0 || mpeg4type->nIDCVLCThreshold != 0 || mpeg4type->bACPred != OMX_TRUE || mpeg4type->nMaxPacketSize != 256 || mpeg4type->nTimeIncRes != 1000 || mpeg4type->nHeaderExtension != 0 || mpeg4type->bReversibleVLC != OMX_FALSE) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } }
174,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Cluster::GetFirstTime() const { const BlockEntry* pEntry; const long status = GetFirst(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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 Cluster::GetFirstTime() const
174,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data) { HashAndString *data = (HashAndString*) user_data; gchar *in = (gchar*) val; g_hash_table_insert (data->hash, g_strdup ((gchar*) key), g_strjoin (" ", data->string, in, NULL)); } Commit Message: CWE ID: CWE-264
hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)
165,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { char buff[1024]; int fd, nr, nw; if (argc < 2) { fprintf(stderr, "usage: %s output-filename\n" " %s |output-command\n" " %s :host:port\n", argv[0], argv[0], argv[0]); return 1; } fd = open_gen_fd(argv[1]); if (fd < 0) { perror("open_gen_fd"); exit(EXIT_FAILURE); } while ((nr = read(0, buff, sizeof (buff))) != 0) { if (nr < 0) { if (errno == EINTR) continue; perror("read"); exit(EXIT_FAILURE); } nw = write(fd, buff, nr); if (nw < 0) { perror("write"); exit(EXIT_FAILURE); } } return 0; } Commit Message: misc oom and possible memory leak fix CWE ID:
int main(int argc, char *argv[]) { char buff[1024]; int fd, nr, nw; if (argc < 2) { fprintf(stderr, "usage: %s output-filename\n" " %s |output-command\n" " %s :host:port\n", argv[0], argv[0], argv[0]); return 1; } fd = open_gen_fd(argv[1]); if (fd < 0) { perror("open_gen_fd"); exit(EXIT_FAILURE); } while ((nr = read(0, buff, sizeof (buff))) != 0) { if (nr < 0) { if (errno == EINTR) continue; perror("read"); exit(EXIT_FAILURE); } nw = write(fd, buff, nr); if (nw < 0) { perror("write"); exit(EXIT_FAILURE); } } close(fd); return 0; }
169,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", is_main_frame: " << params.is_main_frame << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << params.frame_id; GURL validated_url(params.url); RenderProcessHost* render_process_host = render_view_host->GetProcess(); RenderViewHost::FilterURL(render_process_host, false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } render_manager_.RendererAbortedProvisionalLoad(render_view_host); } FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidFailProvisionalLoad(params.frame_id, params.is_main_frame, validated_url, params.error_code, params.error_description, render_view_host)); } Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof. BUG=280512 BUG=278899 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23978003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebContentsImpl::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", is_main_frame: " << params.is_main_frame << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << params.frame_id; GURL validated_url(params.url); RenderProcessHost* render_process_host = render_view_host->GetProcess(); RenderViewHost::FilterURL(render_process_host, false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } render_manager_.RendererAbortedProvisionalLoad(render_view_host); } // Do not usually clear the pending entry if one exists, so that the user's // typed URL is not lost when a navigation fails or is aborted. However, in // cases that we don't show the pending entry (e.g., renderer-initiated // navigations in an existing tab), we don't keep it around. That prevents // spoofs on in-page navigations that don't go through // DidStartProvisionalLoadForFrame. // In general, we allow the view to clear the pending entry and typed URL if // the user requests (e.g., hitting Escape with focus in the address bar). // Note: don't touch the transient entry, since an interstitial may exist. if (controller_.GetPendingEntry() != controller_.GetVisibleEntry()) controller_.DiscardPendingEntry(); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidFailProvisionalLoad(params.frame_id, params.is_main_frame, validated_url, params.error_code, params.error_description, render_view_host)); }
171,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUF_SIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUF_SIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUF_SIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUFSIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUFSIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUFSIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; }
169,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TypingCommand::insertText(Document& document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); VisibleSelection currentSelection = frame->selection().computeVisibleSelectionInDOMTreeDeprecated(); String newText = text; if (compositionType != TextCompositionUpdate) newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion); if (compositionType == TextCompositionConfirm) { if (dispatchTextInputEvent(frame, newText) != DispatchEventResult::NotCanceled) return; } if (selectionForInsertion.isCaret() && newText.isEmpty()) return; document.updateStyleAndLayoutIgnorePendingStylesheets(); const PlainTextRange selectionOffsets = getSelectionOffsets(frame); if (selectionOffsets.isNull()) return; const size_t selectionStart = selectionOffsets.start(); if (TypingCommand* lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) { if (lastTypingCommand->endingSelection() != selectionForInsertion) { lastTypingCommand->setStartingSelection(selectionForInsertion); lastTypingCommand->setEndingVisibleSelection(selectionForInsertion); } lastTypingCommand->setCompositionType(compositionType); lastTypingCommand->setShouldRetainAutocorrectionIndicator( options & RetainAutocorrectionIndicator); lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking); lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion; lastTypingCommand->m_selectionStart = selectionStart; EditingState editingState; EventQueueScope eventQueueScope; lastTypingCommand->insertText(newText, options & SelectInsertedText, &editingState); return; } TypingCommand* command = TypingCommand::create(document, InsertText, newText, options, compositionType); bool changeSelection = selectionForInsertion != currentSelection; if (changeSelection) { command->setStartingSelection(selectionForInsertion); command->setEndingVisibleSelection(selectionForInsertion); } command->m_isIncrementalInsertion = isIncrementalInsertion; command->m_selectionStart = selectionStart; command->apply(); if (changeSelection) { command->setEndingVisibleSelection(currentSelection); frame->selection().setSelection(currentSelection.asSelection()); } } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID:
void TypingCommand::insertText(Document& document, void TypingCommand::insertText( Document& document, const String& text, const SelectionInDOMTree& passedSelectionForInsertion, Options options, TextCompositionType compositionType, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); VisibleSelection currentSelection = frame->selection().computeVisibleSelectionInDOMTreeDeprecated(); const VisibleSelection& selectionForInsertion = createVisibleSelection(passedSelectionForInsertion); String newText = text; if (compositionType != TextCompositionUpdate) newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion); if (compositionType == TextCompositionConfirm) { if (dispatchTextInputEvent(frame, newText) != DispatchEventResult::NotCanceled) return; } if (selectionForInsertion.isCaret() && newText.isEmpty()) return; document.updateStyleAndLayoutIgnorePendingStylesheets(); const PlainTextRange selectionOffsets = getSelectionOffsets(frame); if (selectionOffsets.isNull()) return; const size_t selectionStart = selectionOffsets.start(); if (TypingCommand* lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) { if (lastTypingCommand->endingSelection() != selectionForInsertion) { lastTypingCommand->setStartingSelection(selectionForInsertion); lastTypingCommand->setEndingVisibleSelection(selectionForInsertion); } lastTypingCommand->setCompositionType(compositionType); lastTypingCommand->setShouldRetainAutocorrectionIndicator( options & RetainAutocorrectionIndicator); lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking); lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion; lastTypingCommand->m_selectionStart = selectionStart; EditingState editingState; EventQueueScope eventQueueScope; lastTypingCommand->insertText(newText, options & SelectInsertedText, &editingState); return; } TypingCommand* command = TypingCommand::create(document, InsertText, newText, options, compositionType); bool changeSelection = selectionForInsertion != currentSelection; if (changeSelection) { command->setStartingSelection(selectionForInsertion); command->setEndingVisibleSelection(selectionForInsertion); } command->m_isIncrementalInsertion = isIncrementalInsertion; command->m_selectionStart = selectionStart; command->apply(); if (changeSelection) { command->setEndingVisibleSelection(currentSelection); frame->selection().setSelection(currentSelection.asSelection()); } }
172,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org> CWE ID: CWE-310
void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; }
166,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ps_sd *ps_sd_new(ps_mm *data, const char *key) { php_uint32 hv, slot; ps_sd *sd; int keylen; keylen = strlen(key); sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen); if (!sd) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %d, err %s", mm_available(data->mm), mm_error()); return NULL; } hv = ps_sd_hash(key, keylen); slot = hv & data->hash_max; sd->ctime = 0; sd->hv = hv; sd->data = NULL; sd->alloclen = sd->datalen = 0; memcpy(sd->key, key, keylen + 1); sd->next = data->hash[slot]; data->hash[slot] = sd; data->hash_cnt++; if (!sd->next) { if (data->hash_cnt >= data->hash_max) { hash_split(data); } } ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot)); return sd; } Commit Message: CWE ID: CWE-264
static ps_sd *ps_sd_new(ps_mm *data, const char *key) { php_uint32 hv, slot; ps_sd *sd; int keylen; keylen = strlen(key); sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen); if (!sd) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %ld, err %s", mm_available(data->mm), mm_error()); return NULL; } hv = ps_sd_hash(key, keylen); slot = hv & data->hash_max; sd->ctime = 0; sd->hv = hv; sd->data = NULL; sd->alloclen = sd->datalen = 0; memcpy(sd->key, key, keylen + 1); sd->next = data->hash[slot]; data->hash[slot] = sd; data->hash_cnt++; if (!sd->next) { if (data->hash_cnt >= data->hash_max) { hash_split(data); } } ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot)); return sd; }
164,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Block::Block(long long start, long long size_, long long discard_padding) : m_start(start), m_size(size_), m_track(0), m_timecode(-1), m_flags(0), m_frames(NULL), m_frame_count(-1), m_discard_padding(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
Block::Block(long long start, long long size_, long long discard_padding) :
174,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputImeEventRouter* InputImeEventRouterFactory::GetRouter(Profile* profile) { if (!profile) return nullptr; InputImeEventRouter* router = router_map_[profile]; if (!router) { router = new InputImeEventRouter(profile); router_map_[profile] = router; } return router; } Commit Message: Fix the regression caused by http://crrev.com/c/1288350. Bug: 900124,856135 Change-Id: Ie11ad406bd1ea383dc2a83cc8661076309154865 Reviewed-on: https://chromium-review.googlesource.com/c/1317010 Reviewed-by: Lan Wei <azurewei@chromium.org> Commit-Queue: Shu Chen <shuchen@chromium.org> Cr-Commit-Position: refs/heads/master@{#605282} CWE ID: CWE-416
InputImeEventRouter* InputImeEventRouterFactory::GetRouter(Profile* profile) { if (!profile) return nullptr; // The |router_map_| is keyed by the original profile. // Refers to the comments in |RemoveProfile| method for the reason. profile = profile->GetOriginalProfile(); InputImeEventRouter* router = router_map_[profile]; if (!router) { // The router must attach to the profile from which the extension can // receive events. If |profile| has an off-the-record profile, attach the // off-the-record profile. e.g. In guest mode, the extension is running with // the incognito profile instead of its original profile. router = new InputImeEventRouter(profile->HasOffTheRecordProfile() ? profile->GetOffTheRecordProfile() : profile); router_map_[profile] = router; } return router; }
172,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp) { static gpol_ret ret; kadm5_ret_t ret2; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_principal_ent_rec caller_ent; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpol_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_get_policy"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; ret.code = KADM5_AUTH_GET; if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, NULL, NULL)) ret.code = KADM5_OK; else { ret.code = kadm5_get_principal(handle->lhandle, handle->current_caller, &caller_ent, KADM5_PRINCIPAL_NORMAL_MASK); if (ret.code == KADM5_OK) { if (caller_ent.aux_attributes & KADM5_POLICY && strcmp(caller_ent.policy, arg->name) == 0) { ret.code = KADM5_OK; } else ret.code = KADM5_AUTH_GET; ret2 = kadm5_free_principal_ent(handle->lhandle, &caller_ent); ret.code = ret.code ? ret.code : ret2; } } if (ret.code == KADM5_OK) { ret.code = kadm5_get_policy(handle, arg->name, &ret.rec); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
get_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp) { static gpol_ret ret; kadm5_ret_t ret2; char *prime_arg, *funcname; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_principal_ent_rec caller_ent; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpol_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_get_policy"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; ret.code = KADM5_AUTH_GET; if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, NULL, NULL)) ret.code = KADM5_OK; else { ret.code = kadm5_get_principal(handle->lhandle, handle->current_caller, &caller_ent, KADM5_PRINCIPAL_NORMAL_MASK); if (ret.code == KADM5_OK) { if (caller_ent.aux_attributes & KADM5_POLICY && strcmp(caller_ent.policy, arg->name) == 0) { ret.code = KADM5_OK; } else ret.code = KADM5_AUTH_GET; ret2 = kadm5_free_principal_ent(handle->lhandle, &caller_ent); ret.code = ret.code ? ret.code : ret2; } } if (ret.code == KADM5_OK) { ret.code = kadm5_get_policy(handle, arg->name, &ret.rec); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionTtsPlatformImplChromeOs::IsSpeaking() { if (chromeos::CrosLibrary::Get()->EnsureLoaded()) { return chromeos::CrosLibrary::Get()->GetSpeechSynthesisLibrary()-> IsSpeaking(); } set_error(kCrosLibraryNotLoadedError); return false; } 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 ExtensionTtsPlatformImplChromeOs::IsSpeaking() { bool ExtensionTtsPlatformImplChromeOs::SendsEvent(TtsEventType event_type) { return (event_type == TTS_EVENT_START || event_type == TTS_EVENT_END || event_type == TTS_EVENT_ERROR); } void ExtensionTtsPlatformImplChromeOs::PollUntilSpeechFinishes( int utterance_id) { if (utterance_id != utterance_id_) { // This utterance must have been interrupted or cancelled. return; } chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get(); ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); if (!cros_library->EnsureLoaded()) { controller->OnTtsEvent( utterance_id_, TTS_EVENT_ERROR, 0, kCrosLibraryNotLoadedError); return; } if (!cros_library->GetSpeechSynthesisLibrary()->IsSpeaking()) { controller->OnTtsEvent( utterance_id_, TTS_EVENT_END, utterance_length_, std::string()); return; } MessageLoop::current()->PostDelayedTask( FROM_HERE, method_factory_.NewRunnableMethod( &ExtensionTtsPlatformImplChromeOs::PollUntilSpeechFinishes, utterance_id), kSpeechCheckDelayIntervalMs); }
170,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; } 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::GetCodecDelay() const
174,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void assertObjectHasGCInfo(const void* payload, size_t gcInfoIndex) { ASSERT(HeapObjectHeader::fromPayload(payload)->checkHeader()); #if !defined(COMPONENT_BUILD) ASSERT(HeapObjectHeader::fromPayload(payload)->gcInfoIndex() == gcInfoIndex); #endif } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void assertObjectHasGCInfo(const void* payload, size_t gcInfoIndex) { HeapObjectHeader::fromPayload(payload)->checkHeader(); #if !defined(COMPONENT_BUILD) ASSERT(HeapObjectHeader::fromPayload(payload)->gcInfoIndex() == gcInfoIndex); #endif }
172,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame, bool is_new_navigation) { DocumentState* document_state = DocumentState::FromDataSource(frame->dataSource()); NavigationState* navigation_state = document_state->navigation_state(); if (document_state->commit_load_time().is_null()) document_state->set_commit_load_time(Time::Now()); if (is_new_navigation) { UpdateSessionHistory(frame); page_id_ = next_page_id_++; if (GetLoadingUrl(frame) != GURL("about:swappedout")) { history_list_offset_++; if (history_list_offset_ >= content::kMaxSessionHistoryEntries) history_list_offset_ = content::kMaxSessionHistoryEntries - 1; history_list_length_ = history_list_offset_ + 1; history_page_ids_.resize(history_list_length_, -1); history_page_ids_[history_list_offset_] = page_id_; } } else { if (navigation_state->pending_page_id() != -1 && navigation_state->pending_page_id() != page_id_ && !navigation_state->request_committed()) { UpdateSessionHistory(frame); page_id_ = navigation_state->pending_page_id(); history_list_offset_ = navigation_state->pending_history_list_offset(); DCHECK(history_list_length_ <= 0 || history_list_offset_ < 0 || history_list_offset_ >= history_list_length_ || history_page_ids_[history_list_offset_] == page_id_); } } FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitProvisionalLoad(frame, is_new_navigation)); navigation_state->set_request_committed(true); UpdateURL(frame); completed_client_redirect_src_ = Referrer(); UpdateEncoding(frame, frame->view()->pageEncoding().utf8()); } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame, bool is_new_navigation) { DocumentState* document_state = DocumentState::FromDataSource(frame->dataSource()); NavigationState* navigation_state = document_state->navigation_state(); if (document_state->commit_load_time().is_null()) document_state->set_commit_load_time(Time::Now()); if (is_new_navigation) { UpdateSessionHistory(frame); page_id_ = next_page_id_++; // Don't update history_page_ids_ (etc) for chrome::kSwappedOutURL, since // we don't want to forget the entry that was there, and since we will // never come back to chrome::kSwappedOutURL. Note that we have to call if (GetLoadingUrl(frame) != GURL(chrome::kSwappedOutURL)) { history_list_offset_++; if (history_list_offset_ >= content::kMaxSessionHistoryEntries) history_list_offset_ = content::kMaxSessionHistoryEntries - 1; history_list_length_ = history_list_offset_ + 1; history_page_ids_.resize(history_list_length_, -1); history_page_ids_[history_list_offset_] = page_id_; } } else { if (navigation_state->pending_page_id() != -1 && navigation_state->pending_page_id() != page_id_ && !navigation_state->request_committed()) { UpdateSessionHistory(frame); page_id_ = navigation_state->pending_page_id(); history_list_offset_ = navigation_state->pending_history_list_offset(); DCHECK(history_list_length_ <= 0 || history_list_offset_ < 0 || history_list_offset_ >= history_list_length_ || history_page_ids_[history_list_offset_] == page_id_); } } FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitProvisionalLoad(frame, is_new_navigation)); navigation_state->set_request_committed(true); UpdateURL(frame); completed_client_redirect_src_ = Referrer(); UpdateEncoding(frame, frame->view()->pageEncoding().utf8()); }
171,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __init proc_root_init(void) { struct vfsmount *mnt; int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; mnt = kern_mount_data(&proc_fs_type, &init_pid_ns); if (IS_ERR(mnt)) { unregister_filesystem(&proc_fs_type); return; } init_pid_ns.proc_mnt = mnt; proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); } Commit Message: procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-119
void __init proc_root_init(void) { int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; err = pid_ns_prepare_proc(&init_pid_ns); if (err) { unregister_filesystem(&proc_fs_type); return; } proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); }
165,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void SetUpTestCase() { input_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); } 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
static void SetUpTestCase() { input_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); output_ref_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); #if CONFIG_VP9_HIGHBITDEPTH input16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kInputBufferSize + 1) * sizeof(uint16_t))) + 1; output16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); output16_ref_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); #endif }
174,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Block* SimpleBlock::GetBlock() const { return &m_block; } 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 Block* SimpleBlock::GetBlock() const
174,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int xt_compat_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct compat_xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
int xt_compat_check_entry_offsets(const void *base, int xt_compat_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct compat_xt_entry_target *t; const char *e = base; if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; }
167,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, CallbackWrapper* callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); }
171,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pop_decoder_state (DECODER_STATE ds) { if (!ds->idx) { fprintf (stderr, "ERROR: decoder stack underflow!\n"); abort (); } ds->cur = ds->stack[--ds->idx]; } Commit Message: CWE ID: CWE-20
pop_decoder_state (DECODER_STATE ds) { if (!ds->idx) { fprintf (stderr, "ksba: ber-decoder: stack underflow!\n"); return gpg_error (GPG_ERR_INTERNAL); } ds->cur = ds->stack[--ds->idx]; return 0; }
165,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 i; WORD32 max_dpb_size; WORD32 mv_bank_size_allocated; WORD32 pic_mv_bank_size; sps_t *ps_sps; UWORD8 *pu1_buf; mv_buf_t *ps_mv_buf; /* Initialize MV Bank buffer manager */ ps_sps = ps_codec->s_parse.ps_sps; /* Compute the number of MV Bank buffers needed */ max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1]; /* Allocate one extra MV Bank to handle current frame * In case of asynchronous parsing and processing, number of buffers should increase here * based on when parsing and processing threads are synchronized */ max_dpb_size++; pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base; ps_mv_buf = (mv_buf_t *)pu1_buf; pu1_buf += max_dpb_size * sizeof(mv_buf_t); ps_codec->ps_mv_buf = ps_mv_buf; mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t); /* Compute MV bank size per picture */ pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples)); for(i = 0; i < max_dpb_size; i++) { WORD32 buf_ret; WORD32 num_pu; WORD32 num_ctb; WORD32 pic_size; pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples); num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE); num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE); mv_bank_size_allocated -= pic_mv_bank_size; if(mv_bank_size_allocated < 0) { ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK; return IHEVCD_INSUFFICIENT_MEM_MVBANK; } ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf; pu1_buf += (num_ctb + 1) * sizeof(WORD32); ps_mv_buf->pu1_pic_pu_map = pu1_buf; pu1_buf += num_pu; ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf; pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16)); ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf; pu1_buf += num_pu * sizeof(pu_t); buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i); if(0 != buf_ret) { ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR; return IHEVCD_BUF_MGR_ERROR; } ps_mv_buf++; } return ret; } Commit Message: Check only allocated mv bufs for releasing from reference When checking mv bufs for releasing from reference, unallocated mv bufs were also checked. This issue was fixed by restricting the loop count to allocated number of mv bufs. Bug: 34896906 Bug: 34819017 Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb (cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2) CWE ID:
IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 i; WORD32 max_dpb_size; WORD32 mv_bank_size_allocated; WORD32 pic_mv_bank_size; sps_t *ps_sps; UWORD8 *pu1_buf; mv_buf_t *ps_mv_buf; /* Initialize MV Bank buffer manager */ ps_sps = ps_codec->s_parse.ps_sps; /* Compute the number of MV Bank buffers needed */ max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1]; /* Allocate one extra MV Bank to handle current frame * In case of asynchronous parsing and processing, number of buffers should increase here * based on when parsing and processing threads are synchronized */ max_dpb_size++; ps_codec->i4_max_dpb_size = max_dpb_size; pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base; ps_mv_buf = (mv_buf_t *)pu1_buf; pu1_buf += max_dpb_size * sizeof(mv_buf_t); ps_codec->ps_mv_buf = ps_mv_buf; mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t); /* Compute MV bank size per picture */ pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples)); for(i = 0; i < max_dpb_size; i++) { WORD32 buf_ret; WORD32 num_pu; WORD32 num_ctb; WORD32 pic_size; pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples); num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE); num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE); mv_bank_size_allocated -= pic_mv_bank_size; if(mv_bank_size_allocated < 0) { ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK; return IHEVCD_INSUFFICIENT_MEM_MVBANK; } ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf; pu1_buf += (num_ctb + 1) * sizeof(WORD32); ps_mv_buf->pu1_pic_pu_map = pu1_buf; pu1_buf += num_pu; ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf; pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16)); ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf; pu1_buf += num_pu * sizeof(pu_t); buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i); if(0 != buf_ret) { ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR; return IHEVCD_BUF_MGR_ERROR; } ps_mv_buf++; } return ret; }
173,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionResourceRequestPolicy::CanRequestResource( const GURL& resource_url, const GURL& frame_url, const ExtensionSet* loaded_extensions) { CHECK(resource_url.SchemeIs(chrome::kExtensionScheme)); const Extension* extension = loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url)); if (!extension) { return true; } std::string resource_root_relative_path = resource_url.path().empty() ? "" : resource_url.path().substr(1); if (extension->is_hosted_app() && !extension->icons().ContainsPath(resource_root_relative_path)) { LOG(ERROR) << "Denying load of " << resource_url.spec() << " from " << "hosted app."; return false; } if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableExtensionsResourceWhitelist) && !frame_url.is_empty() && !frame_url.SchemeIs(chrome::kExtensionScheme) && !extension->IsResourceWebAccessible(resource_url.path())) { LOG(ERROR) << "Denying load of " << resource_url.spec() << " which " << "is not a web accessible resource."; return false; } return true; } Commit Message: Do not require DevTools extension resources to be white-listed in manifest. Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is (a) trusted and (b) picky on the frames it loads. This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check. BUG=none TEST=DevToolsExtensionTest.* Review URL: https://chromiumcodereview.appspot.com/9663076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool ExtensionResourceRequestPolicy::CanRequestResource( const GURL& resource_url, const WebKit::WebFrame* frame, const ExtensionSet* loaded_extensions) { CHECK(resource_url.SchemeIs(chrome::kExtensionScheme)); const Extension* extension = loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url)); if (!extension) { return true; } std::string resource_root_relative_path = resource_url.path().empty() ? "" : resource_url.path().substr(1); if (extension->is_hosted_app() && !extension->icons().ContainsPath(resource_root_relative_path)) { LOG(ERROR) << "Denying load of " << resource_url.spec() << " from " << "hosted app."; return false; } GURL frame_url = frame->document().url(); GURL page_url = frame->top()->document().url(); // - devtools (chrome-extension:// URLs are loaded into frames of devtools // to support the devtools extension APIs) if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableExtensionsResourceWhitelist) && !frame_url.is_empty() && !frame_url.SchemeIs(chrome::kExtensionScheme) && !(page_url.SchemeIs(chrome::kChromeDevToolsScheme) && !extension->devtools_url().is_empty()) && !extension->IsResourceWebAccessible(resource_url.path())) { LOG(ERROR) << "Denying load of " << resource_url.spec() << " which " << "is not a web accessible resource."; return false; } return true; }
171,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId __unused, int32_t ioId __unused, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); return 0; }
173,343
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: allocate(struct file *file, int allocate_idat) { struct control *control = png_voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
allocate(struct file *file, int allocate_idat) { struct control *control = voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } }
173,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int http_buf_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int len; /* read bytes from input buffer first */ len = s->buf_end - s->buf_ptr; if (len > 0) { if (len > size) len = size; memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; } else { int64_t target_end = s->end_off ? s->end_off : s->filesize; if ((!s->willclose || s->chunksize < 0) && target_end >= 0 && s->off >= target_end) return AVERROR_EOF; len = ffurl_read(s->hd, buf, size); if (!len && (!s->willclose || s->chunksize < 0) && target_end >= 0 && s->off < target_end) { av_log(h, AV_LOG_ERROR, "Stream ends prematurely at %"PRId64", should be %"PRId64"\n", s->off, target_end ); return AVERROR(EIO); } } if (len > 0) { s->off += len; if (s->chunksize > 0) s->chunksize -= len; } return len; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
static int http_buf_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int len; /* read bytes from input buffer first */ len = s->buf_end - s->buf_ptr; if (len > 0) { if (len > size) len = size; memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; } else { uint64_t target_end = s->end_off ? s->end_off : s->filesize; if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end) return AVERROR_EOF; len = ffurl_read(s->hd, buf, size); if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) { av_log(h, AV_LOG_ERROR, "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n", s->off, target_end ); return AVERROR(EIO); } } if (len > 0) { s->off += len; if (s->chunksize > 0) s->chunksize -= len; } return len; }
168,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_policy_2_svc(cpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
create_policy_2_svc(cpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event = stuff->send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; } Commit Message: CWE ID: CWE-20
XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); send_event = stuff->send_event; result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; }
165,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } } 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
Chapters::~Chapters()
174,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); env->insn_aux_data = new_data; vfree(old_data); return 0; } Commit Message: bpf: fix branch pruning logic when the verifier detects that register contains a runtime constant and it's compared with another constant it will prune exploration of the branch that is guaranteed not to be taken at runtime. This is all correct, but malicious program may be constructed in such a way that it always has a constant comparison and the other branch is never taken under any conditions. In this case such path through the program will not be explored by the verifier. It won't be taken at run-time either, but since all instructions are JITed the malicious program may cause JITs to complain about using reserved fields, etc. To fix the issue we have to track the instructions explored by the verifier and sanitize instructions that are dead at run time with NOPs. We cannot reject such dead code, since llvm generates it for valid C code, since it doesn't do as much data flow analysis as the verifier does. Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)") Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> CWE ID: CWE-20
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; }
167,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_MostVisitedURLsObserver_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); } Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer. BUG=677672 Review-Url: https://codereview.chromium.org/2697543002 Cr-Commit-Position: refs/heads/master@{#449958} CWE ID: CWE-17
void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_Observer_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); }
172,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void uipc_check_interrupt_locked(void) { if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set)) { char sig_recv = 0; recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL); } } 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
static void uipc_check_interrupt_locked(void) { if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set)) { char sig_recv = 0; TEMP_FAILURE_RETRY(recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL)); } }
173,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur, OnWillGpuSwitchOccur) IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled) << msg.type(); return handled; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur, OnWillGpuSwitchOccur) IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled) << msg.type(); return handled; }
170,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: handle_mlppp(netdissect_options *ndo, const u_char *p, int length) { if (!ndo->ndo_eflag) ND_PRINT((ndo, "MLPPP, ")); ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u", (EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */ bittok2str(ppp_ml_flag_values, "none", *p & 0xc0), length)); } Commit Message: CVE-2017-13038/PPP: Do bounds checking. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by Katie Holly. CWE ID: CWE-125
handle_mlppp(netdissect_options *ndo, const u_char *p, int length) { if (!ndo->ndo_eflag) ND_PRINT((ndo, "MLPPP, ")); if (length < 2) { ND_PRINT((ndo, "[|mlppp]")); return; } if (!ND_TTEST_16BITS(p)) { ND_PRINT((ndo, "[|mlppp]")); return; } ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u", (EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */ bittok2str(ppp_ml_flag_values, "none", *p & 0xc0), length)); }
167,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand(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_expand_set(PNG_CONST image_transform *this, image_transform_png_set_expand_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand(pp); if (that->this.has_tRNS) that->this.is_transparent = 1; this->next->set(this->next, that, pp, pi); }
173,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string &element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { *upload_required_ = USE_UPLOAD_RATES; if (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string& element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { // We check for the upload required attribute below, but if it's not // present, we use the default upload rates. Likewise, by default we assume // an empty experiment id. *upload_required_ = USE_UPLOAD_RATES; *experiment_id_ = std::string(); // |attrs| is a NULL-terminated list of (attribute, value) pairs. while (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } else if (attribute_name.compare("experimentid") == 0) { *experiment_id_ = attrs[1]; } // Advance to the next (attribute, value) pair. attrs += 2; } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } }
170,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HeapObjectHeader::zapMagic() { ASSERT(checkHeader()); m_magic = zappedMagic; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void HeapObjectHeader::zapMagic() { checkHeader(); m_magic = zappedMagic; }
172,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks() { TRACE_EVENT0( "cc", "PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks"); DCHECK(should_notify_client_if_no_tasks_are_pending_); check_for_completed_raster_tasks_callback_.Cancel(); check_for_completed_raster_tasks_pending_ = false; CheckForCompletedWorkerTasks(); CheckForCompletedUploads(); FlushUploads(); bool will_notify_client_that_no_tasks_required_for_activation_are_pending = (should_notify_client_if_no_tasks_required_for_activation_are_pending_ && !HasPendingTasksRequiredForActivation()); bool will_notify_client_that_no_tasks_are_pending = (should_notify_client_if_no_tasks_are_pending_ && !HasPendingTasks()); should_notify_client_if_no_tasks_required_for_activation_are_pending_ &= !will_notify_client_that_no_tasks_required_for_activation_are_pending; should_notify_client_if_no_tasks_are_pending_ &= !will_notify_client_that_no_tasks_are_pending; scheduled_raster_task_count_ = 0; if (PendingRasterTaskCount()) ScheduleMoreTasks(); TRACE_EVENT_ASYNC_STEP_INTO1( "cc", "ScheduledTasks", this, StateName(), "state", TracedValue::FromValue(StateAsValue().release())); if (HasPendingTasks()) ScheduleCheckForCompletedRasterTasks(); if (will_notify_client_that_no_tasks_required_for_activation_are_pending) { DCHECK(std::find_if(raster_tasks_required_for_activation().begin(), raster_tasks_required_for_activation().end(), WasCanceled) == raster_tasks_required_for_activation().end()); client()->DidFinishRunningTasksRequiredForActivation(); } if (will_notify_client_that_no_tasks_are_pending) { TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this); DCHECK(!HasPendingTasksRequiredForActivation()); client()->DidFinishRunningTasks(); } } Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks() { TRACE_EVENT0( "cc", "PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks"); DCHECK(should_notify_client_if_no_tasks_are_pending_); check_for_completed_raster_tasks_callback_.Cancel(); check_for_completed_raster_tasks_pending_ = false; CheckForCompletedWorkerTasks(); CheckForCompletedUploads(); FlushUploads(); bool will_notify_client_that_no_tasks_required_for_activation_are_pending = (should_notify_client_if_no_tasks_required_for_activation_are_pending_ && !raster_required_for_activation_finished_task_pending_ && !HasPendingTasksRequiredForActivation()); bool will_notify_client_that_no_tasks_are_pending = (should_notify_client_if_no_tasks_are_pending_ && !raster_finished_task_pending_ && !HasPendingTasks()); should_notify_client_if_no_tasks_required_for_activation_are_pending_ &= !will_notify_client_that_no_tasks_required_for_activation_are_pending; should_notify_client_if_no_tasks_are_pending_ &= !will_notify_client_that_no_tasks_are_pending; scheduled_raster_task_count_ = 0; if (PendingRasterTaskCount()) ScheduleMoreTasks(); TRACE_EVENT_ASYNC_STEP_INTO1( "cc", "ScheduledTasks", this, StateName(), "state", TracedValue::FromValue(StateAsValue().release())); if (HasPendingTasks()) ScheduleCheckForCompletedRasterTasks(); if (will_notify_client_that_no_tasks_required_for_activation_are_pending) { DCHECK(std::find_if(raster_tasks_required_for_activation().begin(), raster_tasks_required_for_activation().end(), WasCanceled) == raster_tasks_required_for_activation().end()); client()->DidFinishRunningTasksRequiredForActivation(); } if (will_notify_client_that_no_tasks_are_pending) { TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this); DCHECK(!HasPendingTasksRequiredForActivation()); client()->DidFinishRunningTasks(); } }
171,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, szTmp.Value() ); fprintf( mailer, szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } } Commit Message: CWE ID: CWE-134
produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, "%s", szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, "%s", szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, "%s", szTmp.Value() ); fprintf( mailer, "%s", szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } }
165,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsSession::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_, host_); } 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 DevToolsSession::SetRenderer(RenderProcessHost* process_host, void DevToolsSession::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { process_host_id_ = process_host_id; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_host_id_, host_); }
172,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(DangerousPatternTLS().Get()); if (!dangerous_pattern) { icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"(\u0131[\u0300-\u0339]|)" R"([ijl]\u0307)", -1, US_INV), 0, status); DangerousPatternTLS().Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Add a few more confusability mapping entries U+0153(œ) => ce U+00E6(æ), U+04D5 (ӕ) => ae U+0499(ҙ) => 3 U+0525(ԥ) => n Bug: 835554, 826019, 836885 Test: components_unittests --gtest_filter=*IDN* Change-Id: Ic89211f70359d3d67cc25c1805b426b72cdb16ae Reviewed-on: https://chromium-review.googlesource.com/1055894 Commit-Queue: Jungshik Shin <jshin@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#558928} CWE ID:
bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(DangerousPatternTLS().Get()); if (!dangerous_pattern) { icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"(\u0131[\u0300-\u0339]|)" R"([ijl]\u0307)", -1, US_INV), 0, status); DangerousPatternTLS().Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); }
173,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InProcessBrowserTest::InProcessBrowserTest() : browser_(NULL), exit_when_last_browser_closes_(true), multi_desktop_test_(false) #if defined(OS_MACOSX) , autorelease_pool_(NULL) #endif // OS_MACOSX { #if defined(OS_MACOSX) base::FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); chrome_path = chrome_path.DirName(); chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath); CHECK(PathService::Override(base::FILE_EXE, chrome_path)); #endif // defined(OS_MACOSX) CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); base::FilePath src_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)); base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data"); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir)); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
InProcessBrowserTest::InProcessBrowserTest() : browser_(NULL), exit_when_last_browser_closes_(true), open_about_blank_on_browser_launch_(true), multi_desktop_test_(false) #if defined(OS_MACOSX) , autorelease_pool_(NULL) #endif // OS_MACOSX { #if defined(OS_MACOSX) base::FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); chrome_path = chrome_path.DirName(); chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath); CHECK(PathService::Override(base::FILE_EXE, chrome_path)); #endif // defined(OS_MACOSX) CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); base::FilePath src_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)); base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data"); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir)); }
171,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringASCIICase(toElement(node)->getAttribute(roleAttr), role); }
171,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } 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
int Chapters::Edition::GetAtomCount() const long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const { return GetTime(pChapters, m_stop_timecode); }
174,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel, int gpu_host_id) { surface_route_id_ = params_in_pixel.route_id; if (params_in_pixel.protection_state_id && params_in_pixel.protection_state_id != protection_state_id_) { DCHECK(!current_surface_); if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } if (ShouldFastACK(params_in_pixel.surface_handle)) { if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } current_surface_ = params_in_pixel.surface_handle; if (!params_in_pixel.skip_ack) released_front_lock_ = NULL; UpdateExternalTexture(); ui::Compositor* compositor = GetCompositor(); if (!compositor) { if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL); } else { DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) != image_transport_clients_.end()); gfx::Size surface_size_in_pixel = image_transport_clients_[params_in_pixel.surface_handle]->size(); gfx::Size surface_size = ConvertSizeToDIP(this, surface_size_in_pixel); window_->SchedulePaintInRect(gfx::Rect(surface_size)); if (!params_in_pixel.skip_ack) { can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params_in_pixel.route_id, gpu_host_id, true)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } } 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 RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( bool RenderWidgetHostViewAura::SwapBuffersPrepare( const gfx::Rect& surface_rect, const gfx::Rect& damage_rect, BufferPresentedParams* params) { DCHECK(params->surface_handle); DCHECK(!params->texture_to_produce); if (last_swapped_surface_size_ != surface_rect.size()) { // The surface could have shrunk since we skipped an update, in which // case we can expect a full update. DLOG_IF(ERROR, damage_rect != surface_rect) << "Expected full damage rect"; skipped_damage_.setEmpty(); last_swapped_surface_size_ = surface_rect.size(); } if (ShouldSkipFrame(surface_rect.size())) { skipped_damage_.op(RectToSkIRect(damage_rect), SkRegion::kUnion_Op); InsertSyncPointAndACK(*params); return false; } DCHECK(!current_surface_ || image_transport_clients_.find(current_surface_) != image_transport_clients_.end()); if (current_surface_) params->texture_to_produce = image_transport_clients_[current_surface_]; std::swap(current_surface_, params->surface_handle); DCHECK(image_transport_clients_.find(current_surface_) != image_transport_clients_.end()); image_transport_clients_[current_surface_]->Consume(surface_rect.size()); released_front_lock_ = NULL; UpdateExternalTexture(); return true; } void RenderWidgetHostViewAura::SwapBuffersCompleted( const BufferPresentedParams& params) { ui::Compositor* compositor = GetCompositor(); if (!compositor) { InsertSyncPointAndACK(params); } else { // Add sending an ACK to the list of things to do OnCompositingDidCommit can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel, int gpu_host_id) { const gfx::Rect surface_rect = gfx::Rect(gfx::Point(), params_in_pixel.size); BufferPresentedParams ack_params( params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle); if (!SwapBuffersPrepare(surface_rect, surface_rect, &ack_params)) return; previous_damage_.setRect(RectToSkIRect(surface_rect)); skipped_damage_.setEmpty(); ui::Compositor* compositor = GetCompositor(); if (compositor) { gfx::Size surface_size = ConvertSizeToDIP(this, params_in_pixel.size); window_->SchedulePaintInRect(gfx::Rect(surface_size)); } SwapBuffersCompleted(ack_params); }
171,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AddExpectationsForSimulatedAttrib0( void AddExpectationsForSimulatedAttrib0WithError( GLsizei num_vertices, GLuint buffer_id, GLenum error) { if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) { return; } EXPECT_CALL(*gl_, GetError()) .WillOnce(Return(GL_NO_ERROR)) .WillOnce(Return(error)) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); if (error == GL_NO_ERROR) { EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } } void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { AddExpectationsForSimulatedAttrib0WithError( num_vertices, buffer_id, GL_NO_ERROR); }
170,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: generate_palette(png_colorp palette, png_bytep trans, int bit_depth, png_const_bytep gamma_table, unsigned int *colors) { /* * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case */ switch (colors[0]) { default: fprintf(stderr, "makepng: --colors=...: invalid count %u\n", colors[0]); exit(1); case 1: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255, gamma_table); return 1; case 2: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], colors[2], gamma_table); return 1; case 3: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255, gamma_table); return 1; case 4: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], colors[4], gamma_table); return 1; case 0: if (bit_depth == 1) { set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table); set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table); return 2; } else { unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */ unsigned int x, y, ip; for (x=0; x<size; ++x) for (y=0; y<size; ++y) { ip = x + (size * y); /* size is at most 16, so the scaled value below fits in 16 bits */ # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2)) # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\ (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\ (size*size)) set_color(palette+ip, trans+ip, /* color: green, red,blue,white */ xyinterp(x, y, 0, 255, 0, 255), xyinterp(x, y, 255, 0, 0, 255), xyinterp(x, y, 0, 0, 255, 255), /* alpha: 0, 102, 204, 255) */ xyinterp(x, y, 0, 102, 204, 255), gamma_table); } return ip+1; } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
generate_palette(png_colorp palette, png_bytep trans, int bit_depth, png_const_bytep gamma_table, unsigned int *colors) { /* * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case */ switch (colors[0]) { default: fprintf(stderr, "makepng: --colors=...: invalid count %u\n", colors[0]); exit(1); case 1: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255, gamma_table); return 1; case 2: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], colors[2], gamma_table); return 1; case 3: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255, gamma_table); return 1; case 4: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], colors[4], gamma_table); return 1; case 0: if (bit_depth == 1) { set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table); set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table); return 2; } else { unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */ unsigned int x, y; volatile unsigned int ip = 0; for (x=0; x<size; ++x) for (y=0; y<size; ++y) { ip = x + (size * y); /* size is at most 16, so the scaled value below fits in 16 bits */ # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2)) # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\ (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\ (size*size)) set_color(palette+ip, trans+ip, /* color: green, red,blue,white */ xyinterp(x, y, 0, 255, 0, 255), xyinterp(x, y, 255, 0, 0, 255), xyinterp(x, y, 0, 0, 255, 255), /* alpha: 0, 102, 204, 255) */ xyinterp(x, y, 0, 102, 204, 255), gamma_table); } return ip+1; } } }
173,579
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Display::Display() { } 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
Chapters::Display::Display()
174,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OomInterventionTabHelper::StartDetectionInRenderer() { auto* config = OomInterventionConfig::GetInstance(); bool renderer_pause_enabled = config->is_renderer_pause_enabled(); bool navigate_ads_enabled = config->is_navigate_ads_enabled(); if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) { DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord()); const std::string& host = web_contents()->GetVisibleURL().host(); if (!decider_->CanTriggerIntervention(host)) { renderer_pause_enabled = false; navigate_ads_enabled = false; } } content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); DCHECK(main_frame); content::RenderProcessHost* render_process_host = main_frame->GetProcess(); DCHECK(render_process_host); content::BindInterface(render_process_host, mojo::MakeRequest(&intervention_)); DCHECK(!binding_.is_bound()); blink::mojom::OomInterventionHostPtr host; binding_.Bind(mojo::MakeRequest(&host)); blink::mojom::DetectionArgsPtr detection_args = config->GetRendererOomDetectionArgs(); intervention_->StartDetection(std::move(host), std::move(detection_args), renderer_pause_enabled, navigate_ads_enabled); } Commit Message: OomIntervention opt-out should work properly with 'show original' OomIntervention should not be re-triggered on the same page if the user declines the intervention once. This CL fixes the bug. Bug: 889131, 887119 Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8 Reviewed-on: https://chromium-review.googlesource.com/1245019 Commit-Queue: Yuzu Saijo <yuzus@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#594574} CWE ID: CWE-119
void OomInterventionTabHelper::StartDetectionInRenderer() { auto* config = OomInterventionConfig::GetInstance(); bool renderer_pause_enabled = config->is_renderer_pause_enabled(); bool navigate_ads_enabled = config->is_navigate_ads_enabled(); if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) { DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord()); const std::string& host = web_contents()->GetVisibleURL().host(); if (!decider_->CanTriggerIntervention(host)) { renderer_pause_enabled = false; navigate_ads_enabled = false; } } if (!renderer_pause_enabled && !navigate_ads_enabled) return; content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); DCHECK(main_frame); content::RenderProcessHost* render_process_host = main_frame->GetProcess(); DCHECK(render_process_host); content::BindInterface(render_process_host, mojo::MakeRequest(&intervention_)); DCHECK(!binding_.is_bound()); blink::mojom::OomInterventionHostPtr host; binding_.Bind(mojo::MakeRequest(&host)); blink::mojom::DetectionArgsPtr detection_args = config->GetRendererOomDetectionArgs(); intervention_->StartDetection(std::move(host), std::move(detection_args), renderer_pause_enabled, navigate_ads_enabled); }
172,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionBookmarksTest() : client_(NULL), model_(NULL), node_(NULL), folder_(NULL) {} Commit Message: Added unit test for new portion of GetMetaInfo API BUG=383600 Review URL: https://codereview.chromium.org/348833003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@278908 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ExtensionBookmarksTest()
171,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; if (offset + size <= i_size_read(inode)) ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; }
167,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_set_end(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(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_set_end(PNG_CONST image_transform *this, image_transform_set_end(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) }
173,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; struct stream packet = *s; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); if (!s_check_rem(s, length + 7)) { rdp_protocol_error("process_secondary_order(), next order pointer would overrun stream", &packet); } next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; }
169,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: ip_printroute(ndo, cp, option_len); break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13022/IP: Add bounds checks to ip_printroute(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
167,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: receive_carbon(void **state) { prof_input("/carbons on"); prof_connect(); assert_true(stbbr_received( "<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>" )); stbbr_send( "<presence to='stabber@localhost' from='buddy1@localhost/mobile'>" "<priority>10</priority>" "<status>On my mobile</status>" "</presence>" ); assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\"")); prof_input("/msg Buddy1"); assert_true(prof_output_exact("unencrypted")); stbbr_send( "<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost'>" "<received xmlns='urn:xmpp:carbons:2'>" "<forwarded xmlns='urn:xmpp:forward:0'>" "<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>" "<body>test carbon from recipient</body>" "</message>" "</forwarded>" "</received>" "</message>" ); assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient")); } Commit Message: Add carbons from check CWE ID: CWE-346
receive_carbon(void **state) { prof_input("/carbons on"); prof_connect(); assert_true(stbbr_received( "<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>" )); stbbr_send( "<presence to='stabber@localhost' from='buddy1@localhost/mobile'>" "<priority>10</priority>" "<status>On my mobile</status>" "</presence>" ); assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\"")); prof_input("/msg Buddy1"); assert_true(prof_output_exact("unencrypted")); stbbr_send( "<message type='chat' to='stabber@localhost/profanity' from='stabber@localhost'>" "<received xmlns='urn:xmpp:carbons:2'>" "<forwarded xmlns='urn:xmpp:forward:0'>" "<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>" "<body>test carbon from recipient</body>" "</message>" "</forwarded>" "</received>" "</message>" ); assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient")); }
168,383
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), interstitial_page_(nullptr), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) }
172,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); }
167,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); if(fmt[strlen(fmt)-1] != '\n') printf("\n"); 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
static void die(const char *fmt, ...) {
174,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TaskService::RunTask(InstanceId instance_id, RunnerId runner_id, base::OnceClosure task) { base::subtle::AutoReadLock task_lock(task_lock_); { base::AutoLock lock(lock_); if (instance_id != bound_instance_id_) return; } std::move(task).Run(); } Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService There are non-trivial performance implications of using shared SRWLocking on Windows as more state has to be checked. Since there are only two uses of the ReadWriteLock in Chromium after over 1 year, the decision is to remove it. BUG=758721 Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80 Reviewed-on: https://chromium-review.googlesource.com/634423 Commit-Queue: Robert Liao <robliao@chromium.org> Reviewed-by: Takashi Toyoshima <toyoshim@chromium.org> Reviewed-by: Francois Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#497632} CWE ID: CWE-20
void TaskService::RunTask(InstanceId instance_id, RunnerId runner_id, base::OnceClosure task) { { base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_); ++tasks_in_flight_; } if (IsInstanceIdStillBound(instance_id)) std::move(task).Run(); { base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_); --tasks_in_flight_; DCHECK_GE(tasks_in_flight_, 0); if (tasks_in_flight_ == 0) no_tasks_in_flight_cv_.Signal(); } } bool TaskService::IsInstanceIdStillBound(InstanceId instance_id) { base::AutoLock lock(lock_); return instance_id == bound_instance_id_; }
172,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) { int code = 0; font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42"); if (!font->font) return gs_throw(gs_error_VMerror, "out of memory"); /* no shortage of things to initialize */ { gs_font_type42 *p42 = (gs_font_type42*) font->font; /* Common to all fonts: */ p42->next = 0; p42->prev = 0; p42->memory = ctx->memory; p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ p42->base = font->font; /* NB also set by gs_definefont later */ p42->is_resource = false; gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); p42->id = gs_next_ids(ctx->memory, 1); p42->client_data = font; /* that's us */ /* this is overwritten in grid_fit() */ gs_make_identity(&p42->FontMatrix); gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ p42->FontType = ft_TrueType; p42->BitmapWidths = false; p42->ExactSize = fbit_use_outlines; p42->InBetweenSize = fbit_use_outlines; p42->TransformedChar = fbit_use_outlines; p42->WMode = 0; p42->PaintType = 0; p42->StrokeWidth = 0; p42->is_cached = 0; p42->procs.define_font = gs_no_define_font; p42->procs.make_font = gs_no_make_font; p42->procs.font_info = gs_type42_font_info; p42->procs.same_font = gs_default_same_font; p42->procs.encode_char = xps_true_callback_encode_char; p42->procs.decode_glyph = xps_true_callback_decode_glyph; p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; p42->procs.glyph_info = gs_type42_glyph_info; p42->procs.glyph_outline = gs_type42_glyph_outline; p42->procs.glyph_name = xps_true_callback_glyph_name; p42->procs.init_fstack = gs_default_init_fstack; p42->procs.next_char_glyph = gs_default_next_char_glyph; p42->procs.build_char = xps_true_callback_build_char; memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); xps_load_sfnt_name(font, (char*)p42->font_name.chars); p42->font_name.size = strlen((char*)p42->font_name.chars); memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); p42->key_name.size = strlen((char*)p42->key_name.chars); /* Base font specific: */ p42->FontBBox.p.x = 0; p42->FontBBox.p.y = 0; p42->FontBBox.q.x = 0; p42->FontBBox.q.y = 0; uid_set_UniqueID(&p42->UID, p42->id); p42->encoding_index = ENCODING_INDEX_UNKNOWN; p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; p42->FAPI = 0; p42->FAPI_font_data = 0; /* Type 42 specific: */ p42->data.string_proc = xps_true_callback_string_proc; p42->data.proc_data = font; gs_type42_font_init(p42, font->subfontid); p42->data.get_glyph_index = xps_true_get_glyph_index; } if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { return(code); } code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); return code; } Commit Message: CWE ID: CWE-119
xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) { int code = 0; font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42"); if (!font->font) return gs_throw(gs_error_VMerror, "out of memory"); /* no shortage of things to initialize */ { gs_font_type42 *p42 = (gs_font_type42*) font->font; /* Common to all fonts: */ p42->next = 0; p42->prev = 0; p42->memory = ctx->memory; p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ p42->base = font->font; /* NB also set by gs_definefont later */ p42->is_resource = false; gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); p42->id = gs_next_ids(ctx->memory, 1); p42->client_data = font; /* that's us */ /* this is overwritten in grid_fit() */ gs_make_identity(&p42->FontMatrix); gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ p42->FontType = ft_TrueType; p42->BitmapWidths = false; p42->ExactSize = fbit_use_outlines; p42->InBetweenSize = fbit_use_outlines; p42->TransformedChar = fbit_use_outlines; p42->WMode = 0; p42->PaintType = 0; p42->StrokeWidth = 0; p42->is_cached = 0; p42->procs.define_font = gs_no_define_font; p42->procs.make_font = gs_no_make_font; p42->procs.font_info = gs_type42_font_info; p42->procs.same_font = gs_default_same_font; p42->procs.encode_char = xps_true_callback_encode_char; p42->procs.decode_glyph = xps_true_callback_decode_glyph; p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; p42->procs.glyph_info = gs_type42_glyph_info; p42->procs.glyph_outline = gs_type42_glyph_outline; p42->procs.glyph_name = xps_true_callback_glyph_name; p42->procs.init_fstack = gs_default_init_fstack; p42->procs.next_char_glyph = gs_default_next_char_glyph; p42->procs.build_char = xps_true_callback_build_char; memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars)); p42->font_name.size = strlen((char*)p42->font_name.chars); memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); p42->key_name.size = strlen((char*)p42->key_name.chars); /* Base font specific: */ p42->FontBBox.p.x = 0; p42->FontBBox.p.y = 0; p42->FontBBox.q.x = 0; p42->FontBBox.q.y = 0; uid_set_UniqueID(&p42->UID, p42->id); p42->encoding_index = ENCODING_INDEX_UNKNOWN; p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; p42->FAPI = 0; p42->FAPI_font_data = 0; /* Type 42 specific: */ p42->data.string_proc = xps_true_callback_string_proc; p42->data.proc_data = font; gs_type42_font_init(p42, font->subfontid); p42->data.get_glyph_index = xps_true_get_glyph_index; } if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { return(code); } code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); return code; }
164,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret <= 0 ? ret : -EIO; } Commit Message: HID: cp2112: fix gpio-callback error handling In case of a zero-length report, the gpio direction_input callback would currently return success instead of an errno. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <stable@vger.kernel.org> # 4.9 Signed-off-by: Johan Hovold <johan@kernel.org> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-388
static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret < 0 ? ret : -EIO; }
168,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); // Change the first tab to be the omnibox page (WebUI). GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new normal tab with a data URL. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); // Create another data URL tab. With Site Isolation, this will require its // own process, but without Site Isolation, it can share the previous // process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); // Create another WebUI tab. It should share the process with omnibox. // Note: intentionally create this tab after the normal tabs to exercise bug // 43448 where extension and WebUI tabs could get combined into normal // renderers. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); // Create an extension tab. It should be in its own process. GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); }
173,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MediaPlayer::setDataSource(const sp<IStreamSource> &source) { ALOGV("setDataSource"); status_t err = UNKNOWN_ERROR; const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(source))) { player.clear(); } err = attachNewPlayer(player); } return err; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
status_t MediaPlayer::setDataSource(const sp<IStreamSource> &source) { ALOGV("setDataSource"); status_t err = UNKNOWN_ERROR; const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(source))) { player.clear(); } err = attachNewPlayer(player); } return err; }
173,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string utf16ToUtf8(const StringPiece16& utf16) { ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length()); if (utf8Length <= 0) { return {}; } std::string utf8; utf8.resize(utf8Length); utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin()); return utf8; } Commit Message: Add bound checks to utf16_to_utf8 Test: ran libaapt2_tests64 Bug: 29250543 Change-Id: I1ebc017af623b6514cf0c493e8cd8e1d59ea26c3 (cherry picked from commit 4781057e78f63e0e99af109cebf3b6a78f4bfbb6) CWE ID: CWE-119
std::string utf16ToUtf8(const StringPiece16& utf16) { ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length()); if (utf8Length <= 0) { return {}; } std::string utf8; // Make room for '\0' explicitly. utf8.resize(utf8Length + 1); utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1); utf8.resize(utf8Length); return utf8; }
174,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, bool presented, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, presented, sync_point)); } 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 RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, uint64 surface_handle, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, surface_handle, sync_point)); }
171,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RendererSchedulerImpl::OnShutdownTaskQueue( const scoped_refptr<MainThreadTaskQueue>& task_queue) { if (main_thread_only().was_shutdown) return; if (task_queue_throttler_) task_queue_throttler_->ShutdownTaskQueue(task_queue.get()); if (task_runners_.erase(task_queue)) { switch (task_queue->queue_class()) { case MainThreadTaskQueue::QueueClass::kTimer: task_queue->RemoveTaskObserver( &main_thread_only().timer_task_cost_estimator); case MainThreadTaskQueue::QueueClass::kLoading: task_queue->RemoveTaskObserver( &main_thread_only().loading_task_cost_estimator); default: break; } } } Commit Message: [scheduler] Remove implicit fallthrough in switch Bail out early when a condition in the switch is fulfilled. This does not change behaviour due to RemoveTaskObserver being no-op when the task observer is not present in the list. R=thakis@chromium.org Bug: 177475 Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd Reviewed-on: https://chromium-review.googlesource.com/891187 Reviewed-by: Nico Weber <thakis@chromium.org> Commit-Queue: Alexander Timin <altimin@chromium.org> Cr-Commit-Position: refs/heads/master@{#532649} CWE ID: CWE-119
void RendererSchedulerImpl::OnShutdownTaskQueue( const scoped_refptr<MainThreadTaskQueue>& task_queue) { if (main_thread_only().was_shutdown) return; if (task_queue_throttler_) task_queue_throttler_->ShutdownTaskQueue(task_queue.get()); if (task_runners_.erase(task_queue)) { switch (task_queue->queue_class()) { case MainThreadTaskQueue::QueueClass::kTimer: task_queue->RemoveTaskObserver( &main_thread_only().timer_task_cost_estimator); break; case MainThreadTaskQueue::QueueClass::kLoading: task_queue->RemoveTaskObserver( &main_thread_only().loading_task_cost_estimator); break; default: break; } } }
172,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableSize = zend_hash_check_size(nSize); ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; } Commit Message: Fix #73832 - leave the table in a safe state if the size is too big. CWE ID: CWE-190
ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; ht->nTableSize = zend_hash_check_size(nSize); }
168,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebGLRenderingContextBase::~WebGLRenderingContextBase() { destruction_in_progress_ = true; DestroyContext(); RestoreEvictedContext(this); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
WebGLRenderingContextBase::~WebGLRenderingContextBase() { destruction_in_progress_ = true; clearProgramCompletionQueries(); DestroyContext(); RestoreEvictedContext(this); }
172,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebString WebPageSerializer::generateMarkOfTheWebDeclaration(const WebURL& url) { return String::format("\n<!-- saved from url=(%04d)%s -->\n", static_cast<int>(url.spec().length()), url.spec().data()); } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20
WebString WebPageSerializer::generateMarkOfTheWebDeclaration(const WebURL& url) { StringBuilder builder; builder.append("\n<!-- "); builder.append(PageSerializer::markOfTheWebDeclaration(url)); builder.append(" -->\n"); return builder.toString(); }
171,787