instruction
stringclasses
1 value
input
stringlengths
90
9.3k
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: int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse hvi check fail", test_parser_hvi); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); }
168,830
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 InputMethodBase::OnInputMethodChanged() const { TextInputClient* client = GetTextInputClient(); if (client && client->GetTextInputType() != TEXT_INPUT_TYPE_NONE) client->OnInputMethodChanged(); } Commit Message: cleanup: Use IsTextInputTypeNone() in OnInputMethodChanged(). BUG=None TEST=None Review URL: http://codereview.chromium.org/8986010 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116461 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void InputMethodBase::OnInputMethodChanged() const { TextInputClient* client = GetTextInputClient(); if (!IsTextInputTypeNone()) client->OnInputMethodChanged(); }
171,062
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::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Undefined(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); if (!entriesValue->IsArray()) return v8::Undefined(m_isolate); v8::Local<v8::Array> entries = entriesValue.As<v8::Array>(); if (!markArrayEntriesAsInternal(context, entries, V8InternalValueType::kEntry)) return v8::Undefined(m_isolate); if (!entries->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return entries; } 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::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Undefined(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); v8::Local<v8::Value> copied; if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, entriesValue).ToLocal(&copied) || !copied->IsArray()) return v8::Undefined(m_isolate); if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kEntry)) return v8::Undefined(m_isolate); return copied; }
172,064
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: stringprep (char *in, size_t maxlen, Stringprep_profile_flags flags, const Stringprep_profile * profile) { int rc; char *utf8 = NULL; uint32_t *ucs4 = NULL; size_t ucs4len, maxucs4len, adducs4len = 50; do { uint32_t *newp; free (ucs4); ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len); maxucs4len = ucs4len + adducs4len; newp = realloc (ucs4, maxucs4len * sizeof (uint32_t)); if (!newp) return STRINGPREP_MALLOC_ERROR; } ucs4 = newp; rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile); adducs4len += 50; } Commit Message: CWE ID: CWE-119
stringprep (char *in, size_t maxlen, Stringprep_profile_flags flags, const Stringprep_profile * profile) { int rc; char *utf8 = NULL; uint32_t *ucs4 = NULL; size_t ucs4len, maxucs4len, adducs4len = 50; do { uint32_t *newp; free (ucs4); ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len); if (ucs4 == NULL) return STRINGPREP_ICONV_ERROR; maxucs4len = ucs4len + adducs4len; newp = realloc (ucs4, maxucs4len * sizeof (uint32_t)); if (!newp) return STRINGPREP_MALLOC_ERROR; } ucs4 = newp; rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile); adducs4len += 50; }
164,762
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 semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = fcntl(semaphore->fd, F_GETFL); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (fcntl(semaphore->fd, F_SETFL, flags) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; } 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
bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_GETFL)); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK)) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags)) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; }
173,483
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 Block::GetTimeCode(const Cluster* pCluster) const { if (pCluster == 0) return m_timecode; const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; //unscaled timecode units } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Block::GetTimeCode(const Cluster* pCluster) const const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; // unscaled timecode units }
174,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: size_t calculate_camera_metadata_entry_data_size(uint8_t type, size_t data_count) { if (type >= NUM_TYPES) return 0; size_t data_bytes = data_count * camera_metadata_type_size[type]; return data_bytes <= 4 ? 0 : ALIGN_TO(data_bytes, DATA_ALIGNMENT); } Commit Message: Camera: Prevent data size overflow Add a function to check overflow when calculating metadata data size. Bug: 30741779 Change-Id: I6405fe608567a4f4113674050f826f305ecae030 CWE ID: CWE-119
size_t calculate_camera_metadata_entry_data_size(uint8_t type,
173,394
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 store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0600); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } copy_file_as_user(src, dest, getuid(), getgid(), 0600); fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,095
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 comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. CWE ID: CWE-416
void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); }
169,753
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 OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, bool in_drag) { const ui::OSExchangeData& data = event.data(); if (data.HasURL()) { GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) { string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); SetUserText(text); if (url.spec().length() == text.length()) model()->AcceptInput(CURRENT_TAB, true); return CopyOrLinkDragOperation(event.source_operations()); } } else if (data.HasString()) { int string_drop_position = drop_highlight_position(); string16 text; if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) { DCHECK(string_drop_position == -1 || ((string_drop_position >= 0) && (string_drop_position <= GetTextLength()))); if (in_drag) { if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE) MoveSelectedText(string_drop_position); else InsertText(string_drop_position, text); } else { PasteAndGo(CollapseWhitespace(text, true)); } return CopyOrLinkDragOperation(event.source_operations()); } } return ui::DragDropTypes::DRAG_NONE; } Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop. BUG=109245 TEST=N/A Review URL: http://codereview.chromium.org/9116016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, bool in_drag) { const ui::OSExchangeData& data = event.data(); if (data.HasURL()) { GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) { string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); SetUserText(text); model()->AcceptInput(CURRENT_TAB, true); return CopyOrLinkDragOperation(event.source_operations()); } } else if (data.HasString()) { int string_drop_position = drop_highlight_position(); string16 text; if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) { DCHECK(string_drop_position == -1 || ((string_drop_position >= 0) && (string_drop_position <= GetTextLength()))); if (in_drag) { if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE) MoveSelectedText(string_drop_position); else InsertText(string_drop_position, text); } else { PasteAndGo(CollapseWhitespace(text, true)); } return CopyOrLinkDragOperation(event.source_operations()); } } return ui::DragDropTypes::DRAG_NONE; }
170,973
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: DefragRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DefragInOrderSimpleTest", DefragInOrderSimpleTest); UtRegisterTest("DefragReverseSimpleTest", DefragReverseSimpleTest); UtRegisterTest("DefragSturgesNovakBsdTest", DefragSturgesNovakBsdTest); UtRegisterTest("DefragSturgesNovakLinuxTest", DefragSturgesNovakLinuxTest); UtRegisterTest("DefragSturgesNovakWindowsTest", DefragSturgesNovakWindowsTest); UtRegisterTest("DefragSturgesNovakSolarisTest", DefragSturgesNovakSolarisTest); UtRegisterTest("DefragSturgesNovakFirstTest", DefragSturgesNovakFirstTest); UtRegisterTest("DefragSturgesNovakLastTest", DefragSturgesNovakLastTest); UtRegisterTest("DefragIPv4NoDataTest", DefragIPv4NoDataTest); UtRegisterTest("DefragIPv4TooLargeTest", DefragIPv4TooLargeTest); UtRegisterTest("IPV6DefragInOrderSimpleTest", IPV6DefragInOrderSimpleTest); UtRegisterTest("IPV6DefragReverseSimpleTest", IPV6DefragReverseSimpleTest); UtRegisterTest("IPV6DefragSturgesNovakBsdTest", IPV6DefragSturgesNovakBsdTest); UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", IPV6DefragSturgesNovakLinuxTest); UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", IPV6DefragSturgesNovakWindowsTest); UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", IPV6DefragSturgesNovakSolarisTest); UtRegisterTest("IPV6DefragSturgesNovakFirstTest", IPV6DefragSturgesNovakFirstTest); UtRegisterTest("IPV6DefragSturgesNovakLastTest", IPV6DefragSturgesNovakLastTest); UtRegisterTest("DefragVlanTest", DefragVlanTest); UtRegisterTest("DefragVlanQinQTest", DefragVlanQinQTest); UtRegisterTest("DefragTrackerReuseTest", DefragTrackerReuseTest); UtRegisterTest("DefragTimeoutTest", DefragTimeoutTest); UtRegisterTest("DefragMfIpv4Test", DefragMfIpv4Test); UtRegisterTest("DefragMfIpv6Test", DefragMfIpv6Test); #endif /* UNITTESTS */ } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DefragInOrderSimpleTest", DefragInOrderSimpleTest); UtRegisterTest("DefragReverseSimpleTest", DefragReverseSimpleTest); UtRegisterTest("DefragSturgesNovakBsdTest", DefragSturgesNovakBsdTest); UtRegisterTest("DefragSturgesNovakLinuxTest", DefragSturgesNovakLinuxTest); UtRegisterTest("DefragSturgesNovakWindowsTest", DefragSturgesNovakWindowsTest); UtRegisterTest("DefragSturgesNovakSolarisTest", DefragSturgesNovakSolarisTest); UtRegisterTest("DefragSturgesNovakFirstTest", DefragSturgesNovakFirstTest); UtRegisterTest("DefragSturgesNovakLastTest", DefragSturgesNovakLastTest); UtRegisterTest("DefragIPv4NoDataTest", DefragIPv4NoDataTest); UtRegisterTest("DefragIPv4TooLargeTest", DefragIPv4TooLargeTest); UtRegisterTest("IPV6DefragInOrderSimpleTest", IPV6DefragInOrderSimpleTest); UtRegisterTest("IPV6DefragReverseSimpleTest", IPV6DefragReverseSimpleTest); UtRegisterTest("IPV6DefragSturgesNovakBsdTest", IPV6DefragSturgesNovakBsdTest); UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", IPV6DefragSturgesNovakLinuxTest); UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", IPV6DefragSturgesNovakWindowsTest); UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", IPV6DefragSturgesNovakSolarisTest); UtRegisterTest("IPV6DefragSturgesNovakFirstTest", IPV6DefragSturgesNovakFirstTest); UtRegisterTest("IPV6DefragSturgesNovakLastTest", IPV6DefragSturgesNovakLastTest); UtRegisterTest("DefragVlanTest", DefragVlanTest); UtRegisterTest("DefragVlanQinQTest", DefragVlanQinQTest); UtRegisterTest("DefragTrackerReuseTest", DefragTrackerReuseTest); UtRegisterTest("DefragTimeoutTest", DefragTimeoutTest); UtRegisterTest("DefragMfIpv4Test", DefragMfIpv4Test); UtRegisterTest("DefragMfIpv6Test", DefragMfIpv6Test); UtRegisterTest("DefragTestBadProto", DefragTestBadProto); #endif /* UNITTESTS */ }
168,301
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: ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(""); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; mime->setTo((const char *)&data[1]); size_t mimeLen = strlen((const char *)&data[1]) + 1; #if 0 uint8_t picType = data[1 + mimeLen]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[2 + mimeLen], encoding); if (size < 2 || size - 2 < mimeLen || size - 2 - mimeLen < descLen) { ALOGW("bogus album art sizes"); return NULL; } *length = size - 2 - mimeLen - descLen; return &data[2 + mimeLen + descLen]; } else { uint8_t encoding = data[0]; if (!memcmp(&data[1], "PNG", 3)) { mime->setTo("image/png"); } else if (!memcmp(&data[1], "JPG", 3)) { mime->setTo("image/jpeg"); } else if (!memcmp(&data[1], "-->", 3)) { mime->setTo("text/plain"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], encoding); *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; } Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information several points in stagefrights mp3 album art code used strlen() to parse user-supplied strings that may be unterminated, resulting in reading beyond the end of a buffer. This changes the code to use strnlen() for 8-bit encodings and strengthens the parsing of 16-bit encodings similarly. It also reworks how we watch for the end-of-buffer to avoid all over-reads. Bug: 32377688 Test: crafted mp3's w/ good/bad cover art. See what showed in play music Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6 (cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb) CWE ID: CWE-200
ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(""); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; size_t consumed = 1; // *always* in an 8-bit encoding size_t mimeLen = StringSize(&data[consumed], size - consumed, 0x00); if (mimeLen > size - consumed) { ALOGW("bogus album art size: mime"); return NULL; } mime->setTo((const char *)&data[consumed]); consumed += mimeLen; #if 0 uint8_t picType = data[consumed]; if (picType != 0x03) { it.next(); continue; } #endif consumed++; if (consumed >= size) { ALOGW("bogus album art size: pic type"); return NULL; } size_t descLen = StringSize(&data[consumed], size - consumed, encoding); consumed += descLen; if (consumed >= size) { ALOGW("bogus album art size: description"); return NULL; } *length = size - consumed; return &data[consumed]; } else { uint8_t encoding = data[0]; if (size <= 5) { return NULL; } if (!memcmp(&data[1], "PNG", 3)) { mime->setTo("image/png"); } else if (!memcmp(&data[1], "JPG", 3)) { mime->setTo("image/jpeg"); } else if (!memcmp(&data[1], "-->", 3)) { mime->setTo("text/plain"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], size - 5, encoding); if (descLen > size - 5) { return NULL; } *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; }
174,062
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 PDFiumEngine::HandleEvent(const pp::InputEvent& event) { DCHECK(!defer_page_unload_); defer_page_unload_ = true; bool rv = false; switch (event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: rv = OnMouseDown(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEUP: rv = OnMouseUp(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: rv = OnMouseMove(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYDOWN: rv = OnKeyDown(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYUP: rv = OnKeyUp(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_CHAR: rv = OnChar(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: { KillTouchTimer(next_touch_timer_id_); pp::TouchInputEvent touch_event(event); if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1) ScheduleTouchTimer(touch_event); break; } case PP_INPUTEVENT_TYPE_TOUCHEND: KillTouchTimer(next_touch_timer_id_); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: KillTouchTimer(next_touch_timer_id_); default: break; } DCHECK(defer_page_unload_); defer_page_unload_ = false; for (int page_index : deferred_page_unloads_) pages_[page_index]->Unload(); deferred_page_unloads_.clear(); return rv; } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#515056} CWE ID: CWE-416
bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) { DCHECK(!defer_page_unload_); defer_page_unload_ = true; bool rv = false; switch (event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: rv = OnMouseDown(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEUP: rv = OnMouseUp(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: rv = OnMouseMove(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYDOWN: rv = OnKeyDown(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYUP: rv = OnKeyUp(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_CHAR: rv = OnChar(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: { KillTouchTimer(next_touch_timer_id_); pp::TouchInputEvent touch_event(event); if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1) ScheduleTouchTimer(touch_event); break; } case PP_INPUTEVENT_TYPE_TOUCHEND: KillTouchTimer(next_touch_timer_id_); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: KillTouchTimer(next_touch_timer_id_); default: break; } DCHECK(defer_page_unload_); defer_page_unload_ = false; // Store the pages to unload away because the act of unloading pages can cause // there to be more pages to unload. We leave those extra pages to be unloaded // on the next go around. std::vector<int> pages_to_unload; std::swap(pages_to_unload, deferred_page_unloads_); for (int page_index : pages_to_unload) pages_[page_index]->Unload(); return rv; }
172,665
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[]) { FILE *fp_rd = stdin; FILE *fp_wr = stdout; FILE *fp_al = NULL; BOOL raw = TRUE; BOOL alpha = FALSE; int argi; for (argi = 1; argi < argc; argi++) { if (argv[argi][0] == '-') { switch (argv[argi][1]) { case 'n': raw = FALSE; break; case 'r': raw = TRUE; break; case 'a': alpha = TRUE; argi++; if ((fp_al = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]); exit (1); } break; case 'h': case '?': usage(); exit(0); break; default: fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unknown option %s\n", argv[argi]); usage(); exit(1); break; } /* end switch */ } else if (fp_rd == stdin) { if ((fp_rd = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: file %s does not exist\n", argv[argi]); exit (1); } } else if (fp_wr == stdout) { if ((fp_wr = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: can not create file %s\n", argv[argi]); exit (1); } } else { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: too many parameters\n"); usage(); exit(1); } } /* end for */ #ifdef __TURBOC__ /* set stdin/stdout if required to binary */ if (fp_rd == stdin) { setmode (STDIN, O_BINARY); } if ((raw) && (fp_wr == stdout)) { setmode (STDOUT, O_BINARY); } #endif /* call the conversion program itself */ if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n"); exit(1); } /* close input file */ fclose (fp_rd); /* close output file */ fclose (fp_wr); /* close alpha file */ if (alpha) fclose (fp_al); return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
int main(int argc, char *argv[]) { FILE *fp_rd = stdin; FILE *fp_wr = stdout; FILE *fp_al = NULL; BOOL raw = TRUE; BOOL alpha = FALSE; int argi; for (argi = 1; argi < argc; argi++) { if (argv[argi][0] == '-') { switch (argv[argi][1]) { case 'n': raw = FALSE; break; case 'r': raw = TRUE; break; case 'a': alpha = TRUE; argi++; if ((fp_al = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]); exit (1); } break; case 'h': case '?': usage(); exit(0); break; default: fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unknown option %s\n", argv[argi]); usage(); exit(1); break; } /* end switch */ } else if (fp_rd == stdin) { if ((fp_rd = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: file %s does not exist\n", argv[argi]); exit (1); } } else if (fp_wr == stdout) { if ((fp_wr = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: can not create file %s\n", argv[argi]); exit (1); } } else { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: too many parameters\n"); usage(); exit(1); } } /* end for */ #ifdef __TURBOC__ /* set stdin/stdout if required to binary */ if (fp_rd == stdin) { setmode (STDIN, O_BINARY); } if ((raw) && (fp_wr == stdout)) { setmode (STDOUT, O_BINARY); } #endif /* call the conversion program itself */ if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n"); exit(1); } /* close input file */ fclose (fp_rd); /* close output file */ fclose (fp_wr); /* close alpha file */ if (alpha) fclose (fp_al); return 0; }
173,722
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 UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy, PrefService* prefs) { int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); total_received += received_content_length; total_original += original_content_length; prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received); prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original); #if defined(OS_ANDROID) || defined(OS_IOS) UpdateContentLengthPrefsForDataReductionProxy( received_content_length, original_content_length, with_data_reduction_proxy_enabled, via_data_reduction_proxy, base::Time::Now(), prefs); #endif // defined(OS_ANDROID) || defined(OS_IOS) } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, DataReductionRequestType data_reduction_type, PrefService* prefs) { int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); total_received += received_content_length; total_original += original_content_length; prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received); prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original); #if defined(OS_ANDROID) || defined(OS_IOS) UpdateContentLengthPrefsForDataReductionProxy( received_content_length, original_content_length, with_data_reduction_proxy_enabled, data_reduction_type, base::Time::Now(), prefs); #endif // defined(OS_ANDROID) || defined(OS_IOS) }
171,327
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: DataReductionProxySettings::~DataReductionProxySettings() { spdy_proxy_auth_enabled_.Destroy(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
DataReductionProxySettings::~DataReductionProxySettings() {
172,559
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: chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8 bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8-bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; }
173,730
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 GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color) { } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color) { notImplemented(); }
170,425
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 WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); } Commit Message: issue #54: fix potential out-of-bounds heap read CWE ID: CWE-125
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }
168,971
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 SoftVorbis::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioVorbis: { const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams = (const OMX_AUDIO_PARAM_VORBISTYPE *)params; if (vorbisParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVorbis::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioVorbis: { const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams = (const OMX_AUDIO_PARAM_VORBISTYPE *)params; if (!isValidOMXParam(vorbisParams)) { return OMX_ErrorBadParameter; } if (vorbisParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,221
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: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj) { switch (mrb_type(obj)) { case MRB_TT_CLASS: case MRB_TT_MODULE: copy_class(mrb, dest, obj); mrb_iv_copy(mrb, dest, obj); mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__")); break; case MRB_TT_OBJECT: case MRB_TT_SCLASS: case MRB_TT_HASH: case MRB_TT_DATA: case MRB_TT_EXCEPTION: mrb_iv_copy(mrb, dest, obj); break; case MRB_TT_ISTRUCT: mrb_istruct_copy(dest, obj); break; default: break; } mrb_funcall(mrb, dest, "initialize_copy", 1, obj); } Commit Message: Should not call `initialize_copy` for `TT_ICLASS`; fix #4027 Since `TT_ICLASS` is a internal object that should never be revealed to Ruby world. CWE ID: CWE-824
init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj) { switch (mrb_type(obj)) { case MRB_TT_ICLASS: copy_class(mrb, dest, obj); return; case MRB_TT_CLASS: case MRB_TT_MODULE: copy_class(mrb, dest, obj); mrb_iv_copy(mrb, dest, obj); mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__")); break; case MRB_TT_OBJECT: case MRB_TT_SCLASS: case MRB_TT_HASH: case MRB_TT_DATA: case MRB_TT_EXCEPTION: mrb_iv_copy(mrb, dest, obj); break; case MRB_TT_ISTRUCT: mrb_istruct_copy(dest, obj); break; default: break; } mrb_funcall(mrb, dest, "initialize_copy", 1, obj); }
169,206
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 UserSelectionScreen::FillMultiProfileUserPrefs( user_manager::User* user, base::DictionaryValue* user_dict, bool is_signin_to_add) { if (!is_signin_to_add) { user_dict->SetBoolean(kKeyMultiProfilesAllowed, true); return; } bool is_user_allowed; ash::mojom::MultiProfileUserBehavior policy; GetMultiProfilePolicy(user, &is_user_allowed, &policy); user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed); user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy)); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::FillMultiProfileUserPrefs( const user_manager::User* user, base::DictionaryValue* user_dict, bool is_signin_to_add) { if (!is_signin_to_add) { user_dict->SetBoolean(kKeyMultiProfilesAllowed, true); return; } bool is_user_allowed; ash::mojom::MultiProfileUserBehavior policy; GetMultiProfilePolicy(user, &is_user_allowed, &policy); user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed); user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy)); }
172,199
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 Browser::ShouldFocusLocationBarByDefault(WebContents* source) { const content::NavigationEntry* entry = source->GetController().GetActiveEntry(); if (entry) { const GURL& url = entry->GetURL(); const GURL& virtual_url = entry->GetVirtualURL(); if ((url.SchemeIs(content::kChromeUIScheme) && url.host_piece() == chrome::kChromeUINewTabHost) || (virtual_url.SchemeIs(content::kChromeUIScheme) && virtual_url.host_piece() == chrome::kChromeUINewTabHost)) { return true; } } return search::NavEntryIsInstantNTP(source, entry); } Commit Message: Don't focus the location bar for NTP navigations in non-selected tabs. BUG=677716 TEST=See bug for repro steps. Review-Url: https://codereview.chromium.org/2624373002 Cr-Commit-Position: refs/heads/master@{#443338} CWE ID:
bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) { // Navigations in background tabs shouldn't change the focus state of the // omnibox, since it's associated with the foreground tab. if (source != tab_strip_model_->GetActiveWebContents()) return false; const content::NavigationEntry* entry = source->GetController().GetActiveEntry(); if (entry) { const GURL& url = entry->GetURL(); const GURL& virtual_url = entry->GetVirtualURL(); if ((url.SchemeIs(content::kChromeUIScheme) && url.host_piece() == chrome::kChromeUINewTabHost) || (virtual_url.SchemeIs(content::kChromeUIScheme) && virtual_url.host_piece() == chrome::kChromeUINewTabHost)) { return true; } } return search::NavEntryIsInstantNTP(source, entry); }
172,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: SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index) Commit Message: Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet CWE ID: CWE-415
SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
167,377
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: DefragIPv4NoDataTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int id = 12; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* This packet has an offset > 0, more frags set to 0 and no data. */ p = BuildTestPacket(id, 1, 0, 'A', 0); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; /* The fragment should have been ignored so no fragments should * have been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragIPv4NoDataTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int id = 12; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* This packet has an offset > 0, more frags set to 0 and no data. */ p = BuildTestPacket(IPPROTO_ICMP, id, 1, 0, 'A', 0); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; /* The fragment should have been ignored so no fragments should * have been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; }
168,296
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 TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, int start, int count) { removed_count_++; } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None [email protected] Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, int start, int count) OVERRIDE { removed_count_++; }
170,471
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: t42_parse_font_matrix( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; (void)T1_ToFixedArray( parser, 6, temp, 3 ); temp_scale = FT_ABS( temp[3] ); /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } Commit Message: CWE ID: CWE-20
t42_parse_font_matrix( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; FT_Int result; result = T1_ToFixedArray( parser, 6, temp, 3 ); if ( result < 6 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; }
165,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: ImageLoader::ImageLoader(Element* element) : m_element(element), m_derefElementTimer(this, &ImageLoader::timerFired), m_hasPendingLoadEvent(false), m_hasPendingErrorEvent(false), m_imageComplete(true), m_loadingImageDocument(false), m_elementIsProtected(false), m_suppressErrorEvents(false) { RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this; } Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer. Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer. This associates it with the frame's Networking timer task queue. BUG=624694 Review-Url: https://codereview.chromium.org/2642103002 Cr-Commit-Position: refs/heads/master@{#444927} CWE ID:
ImageLoader::ImageLoader(Element* element) : m_element(element), m_derefElementTimer(TaskRunnerHelper::get(TaskType::Networking, element->document().frame()), this, &ImageLoader::timerFired), m_hasPendingLoadEvent(false), m_hasPendingErrorEvent(false), m_imageComplete(true), m_loadingImageDocument(false), m_elementIsProtected(false), m_suppressErrorEvents(false) { RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this; }
171,974
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 copyStereo8( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; *dst++ = src[1][i] << 8; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyStereo8( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; *dst++ = src[1][i] << 8; } }
174,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: bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) { DCHECK_LT(index_into_window_, window_size_); DCHECK_LT(playback_rate_, 1.0); DCHECK_NE(playback_rate_, 0.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int input_step = ceil(window_size_ * playback_rate_); AlignToFrameBoundary(&input_step); int output_step = window_size_; DCHECK_LT(input_step, output_step); int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > input_step) bytes_to_crossfade = 0; int intro_crossfade_begin = input_step - bytes_to_crossfade; int intro_crossfade_end = input_step; int outtro_crossfade_begin = output_step - bytes_to_crossfade; if (index_into_window_ < intro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } if (index_into_window_ < intro_crossfade_end) { int offset = index_into_window_ - intro_crossfade_begin; uint8* place_to_copy = crossfade_buffer_.get() + offset; CopyWithoutAdvance(place_to_copy); CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } int audio_buffer_offset = index_into_window_ - intro_crossfade_end; if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_) return false; DCHECK_GE(index_into_window_, intro_crossfade_end); CopyWithoutAdvance(dest, audio_buffer_offset); if (index_into_window_ >= outtro_crossfade_begin) { int offset_into_crossfade_buffer = index_into_window_ - outtro_crossfade_begin; uint8* intro_frame_ptr = crossfade_buffer_.get() + offset_into_crossfade_buffer; OutputCrossfadedFrame(dest, intro_frame_ptr); } index_into_window_ += bytes_per_frame_; return true; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) { bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest, int input_step, int output_step) { // Ensure we don't run into OOB read/write situation. CHECK_LT(input_step, output_step); DCHECK_LT(index_into_window_, window_size_); DCHECK_LT(playback_rate_, 1.0); DCHECK_NE(playback_rate_, 0.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > input_step) bytes_to_crossfade = 0; int intro_crossfade_begin = input_step - bytes_to_crossfade; int intro_crossfade_end = input_step; int outtro_crossfade_begin = output_step - bytes_to_crossfade; if (index_into_window_ < intro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } if (index_into_window_ < intro_crossfade_end) { int offset = index_into_window_ - intro_crossfade_begin; uint8* place_to_copy = crossfade_buffer_.get() + offset; CopyWithoutAdvance(place_to_copy); CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } int audio_buffer_offset = index_into_window_ - intro_crossfade_end; if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_) return false; DCHECK_GE(index_into_window_, intro_crossfade_end); CopyWithoutAdvance(dest, audio_buffer_offset); if (index_into_window_ >= outtro_crossfade_begin) { int offset_into_crossfade_buffer = index_into_window_ - outtro_crossfade_begin; uint8* intro_frame_ptr = crossfade_buffer_.get() + offset_into_crossfade_buffer; OutputCrossfadedFrame(dest, intro_frame_ptr); } index_into_window_ += bytes_per_frame_; return true; }
171,529
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: string16 ExtensionGlobalError::GenerateMessageSection( const ExtensionIdSet* extensions, int template_message_id) { CHECK(extensions); CHECK(template_message_id); string16 message; for (ExtensionIdSet::const_iterator iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* e = extension_service_->GetExtensionById(*iter, true); message += l10n_util::GetStringFUTF16( template_message_id, string16(ASCIIToUTF16(e->name())), l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); } return message; } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
string16 ExtensionGlobalError::GenerateMessageSection( const ExtensionIdSet* extensions, int template_message_id) { CHECK(extensions); CHECK(template_message_id); string16 message; for (ExtensionIdSet::const_iterator iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* e = extension_service_->GetExtensionById(*iter, true); message += l10n_util::GetStringFUTF16(template_message_id, string16(ASCIIToUTF16(e->name()))); } return message; }
170,980
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: _asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) counter_end = der_len - 2; else counter_end = der_len; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; } Commit Message: CWE ID: CWE-399
_asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) { if (der_len < 2) return ASN1_DER_ERROR; counter_end = der_len - 2; } else counter_end = der_len; if (counter_end < counter) return ASN1_DER_ERROR; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; }
165,077
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 UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) { Open(callback); } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
void UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
171,700
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 ChromeMockRenderThread::print_preview_pages_remaining() { return print_preview_pages_remaining_; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int ChromeMockRenderThread::print_preview_pages_remaining() { int ChromeMockRenderThread::print_preview_pages_remaining() const { return print_preview_pages_remaining_; }
170,855
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 SendStatus(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { std::string response = "HTTP/1.1 200 OK\r\n" "Content-Length:2\r\n\r\n" "ok"; mg_write(connection, response.data(), response.length()); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SendStatus(struct mg_connection* connection, void SendOkWithBody(struct mg_connection* connection, const std::string& content) { const char* response_fmt = "HTTP/1.1 200 OK\r\n" "Content-Length:%d\r\n\r\n" "%s"; std::string response = base::StringPrintf( response_fmt, content.length(), content.c_str()); mg_write(connection, response.data(), response.length()); }
170,458
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 SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK(!options.executable); DCHECK(!mapped_file_); if (options.size == 0) return false; uint32 rounded_size = (options.size + 0xffff) & ~0xffff; name_ = ASCIIToWide(options.name == NULL ? "" : *options.name); mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size), name_.empty() ? NULL : name_.c_str()); if (!mapped_file_) return false; created_size_ = options.size; if (GetLastError() == ERROR_ALREADY_EXISTS) { created_size_ = 0; if (!options.open_existing) { Close(); return false; } } return true; } Commit Message: Fix integer overflow in Windows shared memory handling. BUG=164490 Review URL: https://codereview.chromium.org/11450016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171369 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK(!options.executable); DCHECK(!mapped_file_); if (options.size == 0) return false; uint32 rounded_size = (options.size + 0xffff) & ~0xffff; if (rounded_size < options.size) return false; name_ = ASCIIToWide(options.name == NULL ? "" : *options.name); mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size), name_.empty() ? NULL : name_.c_str()); if (!mapped_file_) return false; created_size_ = options.size; if (GetLastError() == ERROR_ALREADY_EXISTS) { created_size_ = 0; if (!options.open_existing) { Close(); return false; } } return true; }
171,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: void HostCache::Set(const Key& key, const Entry& entry, base::TimeTicks now, base::TimeDelta ttl) { TRACE_EVENT0(kNetTracingCategory, "HostCache::Set"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (caching_is_disabled()) return; auto it = entries_.find(key); if (it != entries_.end()) { bool is_stale = it->second.IsStale(now, network_changes_); RecordSet(is_stale ? SET_UPDATE_STALE : SET_UPDATE_VALID, now, &it->second, entry); entries_.erase(it); } else { if (size() == max_entries_) EvictOneEntry(now); RecordSet(SET_INSERT, now, nullptr, entry); } AddEntry(Key(key), Entry(entry, now, ttl, network_changes_)); } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID:
void HostCache::Set(const Key& key, const Entry& entry, base::TimeTicks now, base::TimeDelta ttl) { TRACE_EVENT0(kNetTracingCategory, "HostCache::Set"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (caching_is_disabled()) return; bool result_changed = false; auto it = entries_.find(key); if (it != entries_.end()) { bool is_stale = it->second.IsStale(now, network_changes_); AddressListDeltaType delta = FindAddressListDeltaType(it->second.addresses(), entry.addresses()); RecordSet(is_stale ? SET_UPDATE_STALE : SET_UPDATE_VALID, now, &it->second, entry, delta); result_changed = entry.error() == OK && (it->second.error() != entry.error() || delta != DELTA_IDENTICAL); entries_.erase(it); } else { result_changed = true; if (size() == max_entries_) EvictOneEntry(now); RecordSet(SET_INSERT, now, nullptr, entry, DELTA_DISJOINT); } AddEntry(Key(key), Entry(entry, now, ttl, network_changes_)); if (delegate_ && result_changed) delegate_->ScheduleWrite(); }
172,009
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 omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn) { OMX_ERRORTYPE eRet = OMX_ErrorNone; struct v4l2_format fmt; if (!portDefn) { return OMX_ErrorBadParameter; } DEBUG_PRINT_LOW("omx_vdec::update_portdef"); portDefn->nVersion.nVersion = OMX_SPEC_VERSION; portDefn->nSize = sizeof(portDefn); portDefn->eDomain = OMX_PortDomainVideo; if (drv_ctx.frame_rate.fps_denominator > 0) portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format else { DEBUG_PRINT_ERROR("Error: Divide by zero"); return OMX_ErrorBadParameter; } memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (0 == portDefn->nPortIndex) { portDefn->eDir = OMX_DirInput; portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount; portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size; portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused; portDefn->format.video.eCompressionFormat = eCompressionFormat; portDefn->bEnabled = m_inp_bEnabled; portDefn->bPopulated = m_inp_bPopulated; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.pixelformat = output_capability; } else if (1 == portDefn->nPortIndex) { unsigned int buf_size = 0; if (!client_buffers.update_buffer_req()) { DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed"); return OMX_ErrorHardware; } if (!client_buffers.get_buffer_req(buf_size)) { DEBUG_PRINT_ERROR("update buffer requirements"); return OMX_ErrorHardware; } portDefn->nBufferSize = buf_size; portDefn->eDir = OMX_DirOutput; portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.op_buf.mincount; portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; portDefn->bEnabled = m_out_bEnabled; portDefn->bPopulated = m_out_bPopulated; if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) { DEBUG_PRINT_ERROR("Error in getting color format"); return OMX_ErrorHardware; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; } else { portDefn->eDir = OMX_DirMax; DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } if (is_down_scalar_enabled) { int ret = 0; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution"); return OMX_ErrorHardware; } else { portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width; portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height; portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline; portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0]; } } else { portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height; portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width; portDefn->format.video.nStride = drv_ctx.video_resolution.stride; portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines; } if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) || (portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) { portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16); portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height; } DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d " "SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u", (unsigned int)portDefn->nPortIndex, (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nStride, (unsigned int)portDefn->format.video.nSliceHeight, (unsigned int)portDefn->format.video.eColorFormat, (unsigned int)portDefn->nBufferSize, (unsigned int)portDefn->nBufferCountActual); return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn) { OMX_ERRORTYPE eRet = OMX_ErrorNone; struct v4l2_format fmt; if (!portDefn) { return OMX_ErrorBadParameter; } DEBUG_PRINT_LOW("omx_vdec::update_portdef"); portDefn->nVersion.nVersion = OMX_SPEC_VERSION; portDefn->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE); portDefn->eDomain = OMX_PortDomainVideo; if (drv_ctx.frame_rate.fps_denominator > 0) portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format else { DEBUG_PRINT_ERROR("Error: Divide by zero"); return OMX_ErrorBadParameter; } memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (0 == portDefn->nPortIndex) { portDefn->eDir = OMX_DirInput; portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount; portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size; portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused; portDefn->format.video.eCompressionFormat = eCompressionFormat; portDefn->bEnabled = m_inp_bEnabled; portDefn->bPopulated = m_inp_bPopulated; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.pixelformat = output_capability; } else if (1 == portDefn->nPortIndex) { unsigned int buf_size = 0; if (!client_buffers.update_buffer_req()) { DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed"); return OMX_ErrorHardware; } if (!client_buffers.get_buffer_req(buf_size)) { DEBUG_PRINT_ERROR("update buffer requirements"); return OMX_ErrorHardware; } portDefn->nBufferSize = buf_size; portDefn->eDir = OMX_DirOutput; portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.op_buf.mincount; portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; portDefn->bEnabled = m_out_bEnabled; portDefn->bPopulated = m_out_bPopulated; if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) { DEBUG_PRINT_ERROR("Error in getting color format"); return OMX_ErrorHardware; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; } else { portDefn->eDir = OMX_DirMax; DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } if (is_down_scalar_enabled) { int ret = 0; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution"); return OMX_ErrorHardware; } else { portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width; portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height; portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline; portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0]; } } else { portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height; portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width; portDefn->format.video.nStride = drv_ctx.video_resolution.stride; portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines; } if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) || (portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) { portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16); portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height; } DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d " "SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u", (unsigned int)portDefn->nPortIndex, (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nStride, (unsigned int)portDefn->format.video.nSliceHeight, (unsigned int)portDefn->format.video.eColorFormat, (unsigned int)portDefn->nBufferSize, (unsigned int)portDefn->nBufferCountActual); return eRet; }
173,792
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: do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; size_t chars_read; FILE *tmpfp = 0; char const *tmpname; int tmpfd; pid_t pid; if (! dry_run && ! skip_rest_of_patch) { /* Write ed script to a temporary file. This causes ed to abort on invalid commands such as when line numbers or ranges exceed the number of available lines. When ed reads from a pipe, it rejects invalid commands and treats the next line as a new command, which can lead to arbitrary command execution. */ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0); if (tmpfd == -1) pfatal ("Can't create temporary file %s", quotearg (tmpname)); tmpfp = fdopen (tmpfd, "w+b"); if (! tmpfp) pfatal ("Can't open stream for file %s", quotearg (tmpname)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (chars_read == 2 && strEQ (buf, ".\n")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!tmpfp) return; if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0 || fflush (tmpfp) != 0) write_fatal (); if (lseek (tmpfd, 0, SEEK_SET) == -1) pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname)); if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; *outname_needs_removal = true; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } sprintf (buf, "%s %s%s", editor_program, verbosity == VERBOSE ? "" : "- ", outname); fflush (stdout); pid = fork(); fflush (stdout); else if (pid == 0) { dup2 (tmpfd, 0); execl ("/bin/sh", "sh", "-c", buf, (char *) 0); _exit (2); } else } else { int wstatus; if (waitpid (pid, &wstatus, 0) == -1 || ! WIFEXITED (wstatus) || WEXITSTATUS (wstatus) != 0) fatal ("%s FAILED", editor_program); } } Commit Message: CWE ID: CWE-78
do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; size_t chars_read; FILE *tmpfp = 0; char const *tmpname; int tmpfd; pid_t pid; if (! dry_run && ! skip_rest_of_patch) { /* Write ed script to a temporary file. This causes ed to abort on invalid commands such as when line numbers or ranges exceed the number of available lines. When ed reads from a pipe, it rejects invalid commands and treats the next line as a new command, which can lead to arbitrary command execution. */ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0); if (tmpfd == -1) pfatal ("Can't create temporary file %s", quotearg (tmpname)); tmpfp = fdopen (tmpfd, "w+b"); if (! tmpfp) pfatal ("Can't open stream for file %s", quotearg (tmpname)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (chars_read == 2 && strEQ (buf, ".\n")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!tmpfp) return; if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0 || fflush (tmpfp) != 0) write_fatal (); if (lseek (tmpfd, 0, SEEK_SET) == -1) pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname)); if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; *outname_needs_removal = true; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } fflush (stdout); pid = fork(); fflush (stdout); else if (pid == 0) { dup2 (tmpfd, 0); assert (outname[0] != '!' && outname[0] != '-'); execlp (editor_program, editor_program, "-", outname, (char *) NULL); _exit (2); } else } else { int wstatus; if (waitpid (pid, &wstatus, 0) == -1 || ! WIFEXITED (wstatus) || WEXITSTATUS (wstatus) != 0) fatal ("%s FAILED", editor_program); } }
164,684
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 fpga_reset(void) { if (!check_boco2()) { /* we do not have BOCO2, this is not really used */ return 0; } printf("PCIe reset through GPIO7: "); /* apply PCIe reset via GPIO */ kw_gpio_set_valid(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_direction_output(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 0); udelay(1000*10); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 1); printf(" done\n"); return 0; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int fpga_reset(void) { /* no dedicated reset pin for FPGA */ return 0; }
169,626
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_proxy_open(URLContext *h, const char *uri, int flags) { HTTPContext *s = h->priv_data; char hostname[1024], hoststr[1024]; char auth[1024], pathbuf[1024], *path; char lower_url[100]; int port, ret = 0, attempts = 0; HTTPAuthType cur_auth_type; char *authstr; int new_loc; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port, pathbuf, sizeof(pathbuf), uri); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); path = pathbuf; if (*path == '/') path++; ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port, NULL); redo: ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL, h->protocol_whitelist, h->protocol_blacklist, h); if (ret < 0) return ret; authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth, path, "CONNECT"); snprintf(s->buffer, sizeof(s->buffer), "CONNECT %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "%s%s" "\r\n", path, hoststr, authstr ? "Proxy-" : "", authstr ? authstr : ""); av_freep(&authstr); if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto fail; s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->filesize = -1; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the * HTTP header. If tunneling a protocol where the server starts * the conversation, we might buffer part of that here, too. * Reading that requires using the proper ffurl_read() function * on this URLContext, not using the fd directly (as the tls * protocol does). This shouldn't be an issue for tls though, * since the client starts the conversation there, so there * is no extra data that we might buffer up here. */ ret = http_read_header(h, &new_loc); if (ret < 0) goto fail; attempts++; if (s->http_code == 407 && (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) { ffurl_closep(&s->hd); goto redo; } if (s->http_code < 400) return 0; ret = ff_http_averror(s->http_code, AVERROR(EIO)); fail: http_proxy_close(h); return ret; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static int http_proxy_open(URLContext *h, const char *uri, int flags) { HTTPContext *s = h->priv_data; char hostname[1024], hoststr[1024]; char auth[1024], pathbuf[1024], *path; char lower_url[100]; int port, ret = 0, attempts = 0; HTTPAuthType cur_auth_type; char *authstr; int new_loc; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port, pathbuf, sizeof(pathbuf), uri); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); path = pathbuf; if (*path == '/') path++; ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port, NULL); redo: ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL, h->protocol_whitelist, h->protocol_blacklist, h); if (ret < 0) return ret; authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth, path, "CONNECT"); snprintf(s->buffer, sizeof(s->buffer), "CONNECT %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "%s%s" "\r\n", path, hoststr, authstr ? "Proxy-" : "", authstr ? authstr : ""); av_freep(&authstr); if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto fail; s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->filesize = UINT64_MAX; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the * HTTP header. If tunneling a protocol where the server starts * the conversation, we might buffer part of that here, too. * Reading that requires using the proper ffurl_read() function * on this URLContext, not using the fd directly (as the tls * protocol does). This shouldn't be an issue for tls though, * since the client starts the conversation there, so there * is no extra data that we might buffer up here. */ ret = http_read_header(h, &new_loc); if (ret < 0) goto fail; attempts++; if (s->http_code == 407 && (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) { ffurl_closep(&s->hd); goto redo; } if (s->http_code < 400) return 0; ret = ff_http_averror(s->http_code, AVERROR(EIO)); fail: http_proxy_close(h); return ret; }
168,499
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: TaskService::TaskService() : next_instance_id_(0), bound_instance_id_(kInvalidInstanceId) {} 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 <[email protected]> Reviewed-by: Takashi Toyoshima <[email protected]> Reviewed-by: Francois Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#497632} CWE ID: CWE-20
TaskService::TaskService()
172,213
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 AudioRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, int input_channels) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); uint32 buffer_size = media::AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(buffer_size, 0U); DCHECK_LE(buffer_size, static_cast<uint32>(media::limits::kMaxPacketSizeInBytes)); DCHECK_GE(input_channels, 0); DCHECK_LT(input_channels, media::limits::kMaxChannels); int output_memory_size = AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(output_memory_size, 0); int frames = audio_params.frames_per_buffer(); int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames); DCHECK_GE(input_memory_size, 0); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 io_buffer_size = output_memory_size + input_memory_size; uint32 shared_memory_size = media::TotalSharedMemorySizeInBytes(io_buffer_size); if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioSyncReader> reader( new AudioSyncReader(&entry->shared_memory, params, input_channels)); if (!reader->Init()) { SendErrorMessage(stream_id); return; } entry->reader.reset(reader.release()); entry->controller = media::AudioOutputController::Create( audio_manager_, this, audio_params, entry->reader.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); if (media_observer_) media_observer_->OnSetAudioStreamStatus(this, stream_id, "created"); } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void AudioRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, int input_channels) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // media::AudioParameters is validated in the deserializer. if (input_channels < 0 || input_channels > media::limits::kMaxChannels || LookupById(stream_id) != NULL) { SendErrorMessage(stream_id); return; } media::AudioParameters audio_params(params); int output_memory_size = AudioBus::CalculateMemorySize(audio_params); int frames = audio_params.frames_per_buffer(); int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 io_buffer_size = output_memory_size + input_memory_size; uint32 shared_memory_size = media::TotalSharedMemorySizeInBytes(io_buffer_size); if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioSyncReader> reader( new AudioSyncReader(&entry->shared_memory, params, input_channels)); if (!reader->Init()) { SendErrorMessage(stream_id); return; } entry->reader.reset(reader.release()); entry->controller = media::AudioOutputController::Create( audio_manager_, this, audio_params, entry->reader.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); if (media_observer_) media_observer_->OnSetAudioStreamStatus(this, stream_id, "created"); }
171,525
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: EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } RefPtr<EntrySyncCallbackHelper> resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); } 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
EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } EntrySyncCallbackHelper* resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); }
171,433
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 mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } } Commit Message: IB/rxe: Fix mem_check_range integer overflow Update the range check to avoid integer-overflow in edge case. Resolves CVE 2016-8636. Signed-off-by: Eyal Itkin <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Leon Romanovsky <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-190
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }
168,773
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 struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; } Commit Message: ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: [email protected] Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, KERN_ERR, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; }
166,109
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 read_request(int fd, debugger_request_t* out_request) { ucred cr; socklen_t len = sizeof(cr); int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (status != 0) { ALOGE("cannot get credentials"); return -1; } ALOGV("reading tid"); fcntl(fd, F_SETFL, O_NONBLOCK); pollfd pollfds[1]; pollfds[0].fd = fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000)); if (status != 1) { ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid); return -1; } debugger_msg_t msg; memset(&msg, 0, sizeof(msg)); status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg))); if (status < 0) { ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid); return -1; } if (status != sizeof(debugger_msg_t)) { ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid); return -1; } out_request->action = static_cast<debugger_action_t>(msg.action); out_request->tid = msg.tid; out_request->pid = cr.pid; out_request->uid = cr.uid; out_request->gid = cr.gid; out_request->abort_msg_address = msg.abort_msg_address; out_request->original_si_code = msg.original_si_code; if (msg.action == DEBUGGER_ACTION_CRASH) { char buf[64]; struct stat s; snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid); if (stat(buf, &s)) { ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid, out_request->pid); return -1; } } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) { status = get_process_info(out_request->tid, &out_request->pid, &out_request->uid, &out_request->gid); if (status < 0) { ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid); return -1; } if (!selinux_action_allowed(fd, out_request)) return -1; } else { return -1; } return 0; } Commit Message: debuggerd: verify that traced threads belong to the right process. Fix two races in debuggerd's PTRACE_ATTACH logic: 1. The target thread in a crash dump request could exit between the /proc/<pid>/task/<tid> check and the PTRACE_ATTACH. 2. Sibling threads could exit between listing /proc/<pid>/task and the PTRACE_ATTACH. Bug: http://b/29555636 Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591 CWE ID: CWE-264
static int read_request(int fd, debugger_request_t* out_request) { ucred cr; socklen_t len = sizeof(cr); int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (status != 0) { ALOGE("cannot get credentials"); return -1; } ALOGV("reading tid"); fcntl(fd, F_SETFL, O_NONBLOCK); pollfd pollfds[1]; pollfds[0].fd = fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000)); if (status != 1) { ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid); return -1; } debugger_msg_t msg; memset(&msg, 0, sizeof(msg)); status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg))); if (status < 0) { ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid); return -1; } if (status != sizeof(debugger_msg_t)) { ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid); return -1; } out_request->action = static_cast<debugger_action_t>(msg.action); out_request->tid = msg.tid; out_request->pid = cr.pid; out_request->uid = cr.uid; out_request->gid = cr.gid; out_request->abort_msg_address = msg.abort_msg_address; out_request->original_si_code = msg.original_si_code; if (msg.action == DEBUGGER_ACTION_CRASH) { // This check needs to happen again after ptracing the requested thread to prevent a race. if (!pid_contains_tid(out_request->pid, out_request->tid)) { ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid, out_request->pid); return -1; } } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) { status = get_process_info(out_request->tid, &out_request->pid, &out_request->uid, &out_request->gid); if (status < 0) { ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid); return -1; } if (!selinux_action_allowed(fd, out_request)) return -1; } else { return -1; } return 0; }
173,407
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 Ins_MDRP( INS_ARG ) { Int point; TT_F26Dot6 distance, org_dist; point = (Int)args[0]; if ( BOUNDS( args[0], CUR.zp1.n_points ) ) { /* Current version of FreeType silently ignores this out of bounds error * and drops the instruction, see bug #691121 return; } /* XXX: Is there some undocumented feature while in the */ /* twilight zone? */ org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] - CUR.zp0.org_x[CUR.GS.rp0], CUR.zp1.org_y[point] - CUR.zp0.org_y[CUR.GS.rp0] ); /* single width cutin test */ if ( ABS(org_dist) < CUR.GS.single_width_cutin ) { if ( org_dist >= 0 ) org_dist = CUR.GS.single_width_value; else org_dist = -CUR.GS.single_width_value; } /* round flag */ if ( (CUR.opcode & 4) != 0 ) distance = CUR_Func_round( org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); else distance = Round_None( EXEC_ARGS org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); /* minimum distance flag */ if ( (CUR.opcode & 8) != 0 ) { if ( org_dist >= 0 ) { if ( distance < CUR.GS.minimum_distance ) distance = CUR.GS.minimum_distance; } else { if ( distance > -CUR.GS.minimum_distance ) distance = -CUR.GS.minimum_distance; } } /* now move the point */ org_dist = CUR_Func_project( CUR.zp1.cur_x[point] - CUR.zp0.cur_x[CUR.GS.rp0], CUR.zp1.cur_y[point] - CUR.zp0.cur_y[CUR.GS.rp0] ); CUR_Func_move( &CUR.zp1, point, distance - org_dist ); CUR.GS.rp1 = CUR.GS.rp0; CUR.GS.rp2 = point; if ( (CUR.opcode & 16) != 0 ) CUR.GS.rp0 = point; } Commit Message: CWE ID: CWE-125
static void Ins_MDRP( INS_ARG ) { Int point; TT_F26Dot6 distance, org_dist; point = (Int)args[0]; if ( BOUNDS( args[0], CUR.zp1.n_points ) || BOUNDS( CUR.GS.rp0, CUR.zp0.n_points) ) { /* Current version of FreeType silently ignores this out of bounds error * and drops the instruction, see bug #691121 return; } /* XXX: Is there some undocumented feature while in the */ /* twilight zone? */ org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] - CUR.zp0.org_x[CUR.GS.rp0], CUR.zp1.org_y[point] - CUR.zp0.org_y[CUR.GS.rp0] ); /* single width cutin test */ if ( ABS(org_dist) < CUR.GS.single_width_cutin ) { if ( org_dist >= 0 ) org_dist = CUR.GS.single_width_value; else org_dist = -CUR.GS.single_width_value; } /* round flag */ if ( (CUR.opcode & 4) != 0 ) distance = CUR_Func_round( org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); else distance = Round_None( EXEC_ARGS org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); /* minimum distance flag */ if ( (CUR.opcode & 8) != 0 ) { if ( org_dist >= 0 ) { if ( distance < CUR.GS.minimum_distance ) distance = CUR.GS.minimum_distance; } else { if ( distance > -CUR.GS.minimum_distance ) distance = -CUR.GS.minimum_distance; } } /* now move the point */ org_dist = CUR_Func_project( CUR.zp1.cur_x[point] - CUR.zp0.cur_x[CUR.GS.rp0], CUR.zp1.cur_y[point] - CUR.zp0.cur_y[CUR.GS.rp0] ); CUR_Func_move( &CUR.zp1, point, distance - org_dist ); CUR.GS.rp1 = CUR.GS.rp0; CUR.GS.rp2 = point; if ( (CUR.opcode & 16) != 0 ) CUR.GS.rp0 = point; }
164,780
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 PPB_NaCl_Private* GetNaclInterface() { pp::Module *module = pp::Module::Get(); CHECK(module); return static_cast<const PPB_NaCl_Private*>( module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE)); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
const PPB_NaCl_Private* GetNaclInterface() {
170,741
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: SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; }
164,834
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 long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd) { struct socket *sock, *oldsock; struct vhost_virtqueue *vq; struct vhost_net_virtqueue *nvq; struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL; int r; mutex_lock(&n->dev.mutex); r = vhost_dev_check_owner(&n->dev); if (r) goto err; if (index >= VHOST_NET_VQ_MAX) { r = -ENOBUFS; goto err; } vq = &n->vqs[index].vq; nvq = &n->vqs[index]; mutex_lock(&vq->mutex); /* Verify that ring has been setup correctly. */ if (!vhost_vq_access_ok(vq)) { r = -EFAULT; goto err_vq; } sock = get_socket(fd); if (IS_ERR(sock)) { r = PTR_ERR(sock); goto err_vq; } /* start polling new socket */ oldsock = rcu_dereference_protected(vq->private_data, lockdep_is_held(&vq->mutex)); if (sock != oldsock) { ubufs = vhost_net_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock)); if (IS_ERR(ubufs)) { r = PTR_ERR(ubufs); goto err_ubufs; } vhost_net_disable_vq(n, vq); rcu_assign_pointer(vq->private_data, sock); r = vhost_init_used(vq); if (r) goto err_used; r = vhost_net_enable_vq(n, vq); if (r) goto err_used; oldubufs = nvq->ubufs; nvq->ubufs = ubufs; n->tx_packets = 0; n->tx_zcopy_err = 0; n->tx_flush = false; } mutex_unlock(&vq->mutex); if (oldubufs) { vhost_net_ubuf_put_and_wait(oldubufs); mutex_lock(&vq->mutex); vhost_zerocopy_signal_used(n, vq); mutex_unlock(&vq->mutex); } if (oldsock) { vhost_net_flush_vq(n, index); fput(oldsock->file); } mutex_unlock(&n->dev.mutex); return 0; err_used: rcu_assign_pointer(vq->private_data, oldsock); vhost_net_enable_vq(n, vq); if (ubufs) vhost_net_ubuf_put_and_wait(ubufs); err_ubufs: fput(sock->file); err_vq: mutex_unlock(&vq->mutex); err: mutex_unlock(&n->dev.mutex); return r; } Commit Message: vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd) { struct socket *sock, *oldsock; struct vhost_virtqueue *vq; struct vhost_net_virtqueue *nvq; struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL; int r; mutex_lock(&n->dev.mutex); r = vhost_dev_check_owner(&n->dev); if (r) goto err; if (index >= VHOST_NET_VQ_MAX) { r = -ENOBUFS; goto err; } vq = &n->vqs[index].vq; nvq = &n->vqs[index]; mutex_lock(&vq->mutex); /* Verify that ring has been setup correctly. */ if (!vhost_vq_access_ok(vq)) { r = -EFAULT; goto err_vq; } sock = get_socket(fd); if (IS_ERR(sock)) { r = PTR_ERR(sock); goto err_vq; } /* start polling new socket */ oldsock = rcu_dereference_protected(vq->private_data, lockdep_is_held(&vq->mutex)); if (sock != oldsock) { ubufs = vhost_net_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock)); if (IS_ERR(ubufs)) { r = PTR_ERR(ubufs); goto err_ubufs; } vhost_net_disable_vq(n, vq); rcu_assign_pointer(vq->private_data, sock); r = vhost_init_used(vq); if (r) goto err_used; r = vhost_net_enable_vq(n, vq); if (r) goto err_used; oldubufs = nvq->ubufs; nvq->ubufs = ubufs; n->tx_packets = 0; n->tx_zcopy_err = 0; n->tx_flush = false; } mutex_unlock(&vq->mutex); if (oldubufs) { vhost_net_ubuf_put_wait_and_free(oldubufs); mutex_lock(&vq->mutex); vhost_zerocopy_signal_used(n, vq); mutex_unlock(&vq->mutex); } if (oldsock) { vhost_net_flush_vq(n, index); fput(oldsock->file); } mutex_unlock(&n->dev.mutex); return 0; err_used: rcu_assign_pointer(vq->private_data, oldsock); vhost_net_enable_vq(n, vq); if (ubufs) vhost_net_ubuf_put_wait_and_free(ubufs); err_ubufs: fput(sock->file); err_vq: mutex_unlock(&vq->mutex); err: mutex_unlock(&n->dev.mutex); return r; }
166,020
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: XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); } Commit Message: CWE ID: CWE-284
XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2) && rep.nElts <= (rep.length << 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); }
164,917
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 ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; for (i = 0; i < numcmpts; ++i) { data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)); assert(data[i]); } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { return -1; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { return -1; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { return -1; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { return -1; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); } return 0; } Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested with assertions instead of being gracefully handled. CWE ID:
static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; assert(numcmpts <= 3); for (i = 0; i < 3; ++i) { data[i] = 0; } for (i = 0; i < numcmpts; ++i) { if (!(data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)))) { goto error; } } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { goto error; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { goto error; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { goto error; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { goto error; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); data[i] = 0; } return 0; error: for (i = 0; i < numcmpts; ++i) { if (data[i]) { jas_matrix_destroy(data[i]); } } return -1; }
168,741
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: ProcXSendExtensionEvent(ClientPtr client) { int ret; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); if (!((EXTENSION_EVENT_BASE <= first->u.u.type) && (first->u.u.type < lastEvent))) { client->errorValue = first->u.u.type; return BadValue; } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; } Commit Message: CWE ID: CWE-119
ProcXSendExtensionEvent(ClientPtr client) { int ret, i; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); for (i = 0; i < stuff->num_events; i++) { if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) && (first[i].u.u.type < lastEvent))) { client->errorValue = first[i].u.u.type; return BadValue; } } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; }
164,765
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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> 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: SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(NULL), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); }
174,171
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 FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { OnStartLoading(expected_content_size); if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } } Commit Message: Fix use-after-free in FileReaderLoader. Anything that calls out to client_ can cause FileReaderLoader to be destroyed, so make sure to check for that situation. Bug: 835639 Change-Id: I57533d41b7118c06da17abec28bbf301e1f50646 Reviewed-on: https://chromium-review.googlesource.com/1024450 Commit-Queue: Marijn Kruisselbrink <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Reviewed-by: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#552807} CWE ID: CWE-416
void FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { auto weak_this = weak_factory_.GetWeakPtr(); OnStartLoading(expected_content_size); // OnStartLoading calls out to our client, which could delete |this|, so bail // out if that happened. if (!weak_this) return; if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } }
173,218
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 SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect); if (attrName == SVGNames::typeAttr) return colorMatrix->setType(m_type->currentValue()->enumValue()); if (attrName == SVGNames::valuesAttr) return colorMatrix->setValues(m_values->currentValue()->toFloatVector()); ASSERT_NOT_REACHED(); return false; } Commit Message: Explicitly enforce values size in feColorMatrix. [email protected] BUG=468519 Review URL: https://codereview.chromium.org/1075413002 git-svn-id: svn://svn.chromium.org/blink/trunk@193571 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect); if (attrName == SVGNames::typeAttr) return colorMatrix->setType(m_type->currentValue()->enumValue()); if (attrName == SVGNames::valuesAttr) { Vector<float> values = m_values->currentValue()->toFloatVector(); if (values.size() == 20) return colorMatrix->setValues(m_values->currentValue()->toFloatVector()); return false; } ASSERT_NOT_REACHED(); return false; }
171,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic, unsigned long addr, unsigned long length) { unsigned long result = 0; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16) | (IOAPIC_VERSION_ID & 0xff)); break; case IOAPIC_REG_APIC_ID: case IOAPIC_REG_ARB_ID: result = ((ioapic->id & 0xf) << 24); break; default: { u32 redir_index = (ioapic->ioregsel - 0x10) >> 1; u64 redir_content; ASSERT(redir_index < IOAPIC_NUM_PINS); redir_content = ioapic->redirtbl[redir_index].bits; result = (ioapic->ioregsel & 0x1) ? (redir_content >> 32) & 0xffffffff : redir_content & 0xffffffff; break; } } return result; } Commit Message: KVM: Fix bounds checking in ioapic indirect register reads (CVE-2013-1798) If the guest specifies a IOAPIC_REG_SELECT with an invalid value and follows that with a read of the IOAPIC_REG_WINDOW KVM does not properly validate that request. ioapic_read_indirect contains an ASSERT(redir_index < IOAPIC_NUM_PINS), but the ASSERT has no effect in non-debug builds. In recent kernels this allows a guest to cause a kernel oops by reading invalid memory. In older kernels (pre-3.3) this allows a guest to read from large ranges of host memory. Tested: tested against apic unit tests. Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-20
static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic, unsigned long addr, unsigned long length) { unsigned long result = 0; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16) | (IOAPIC_VERSION_ID & 0xff)); break; case IOAPIC_REG_APIC_ID: case IOAPIC_REG_ARB_ID: result = ((ioapic->id & 0xf) << 24); break; default: { u32 redir_index = (ioapic->ioregsel - 0x10) >> 1; u64 redir_content; if (redir_index < IOAPIC_NUM_PINS) redir_content = ioapic->redirtbl[redir_index].bits; else redir_content = ~0ULL; result = (ioapic->ioregsel & 0x1) ? (redir_content >> 32) & 0xffffffff : redir_content & 0xffffffff; break; } } return result; }
166,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: static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); }
169,946
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: rpl_print(netdissect_options *ndo, const struct icmp6_hdr *hdr, const u_char *bp, u_int length) { int secured = hdr->icmp6_code & 0x80; int basecode= hdr->icmp6_code & 0x7f; if(secured) { ND_PRINT((ndo, ", (SEC) [worktodo]")); /* XXX * the next header pointer needs to move forward to * skip the secure part. */ return; } else { ND_PRINT((ndo, ", (CLR)")); } switch(basecode) { case ND_RPL_DAG_IS: ND_PRINT((ndo, "DODAG Information Solicitation")); if(ndo->ndo_vflag) { } break; case ND_RPL_DAG_IO: ND_PRINT((ndo, "DODAG Information Object")); if(ndo->ndo_vflag) { rpl_dio_print(ndo, bp, length); } break; case ND_RPL_DAO: ND_PRINT((ndo, "Destination Advertisement Object")); if(ndo->ndo_vflag) { rpl_dao_print(ndo, bp, length); } break; case ND_RPL_DAO_ACK: ND_PRINT((ndo, "Destination Advertisement Object Ack")); if(ndo->ndo_vflag) { rpl_daoack_print(ndo, bp, length); } break; default: ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code)); break; } return; #if 0 trunc: ND_PRINT((ndo," [|truncated]")); return; #endif } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_print(netdissect_options *ndo, const struct icmp6_hdr *hdr, const u_char *bp, u_int length) { int secured = hdr->icmp6_code & 0x80; int basecode= hdr->icmp6_code & 0x7f; if(secured) { ND_PRINT((ndo, ", (SEC) [worktodo]")); /* XXX * the next header pointer needs to move forward to * skip the secure part. */ return; } else { ND_PRINT((ndo, ", (CLR)")); } switch(basecode) { case ND_RPL_DAG_IS: ND_PRINT((ndo, "DODAG Information Solicitation")); if(ndo->ndo_vflag) { } break; case ND_RPL_DAG_IO: ND_PRINT((ndo, "DODAG Information Object")); if(ndo->ndo_vflag) { rpl_dio_print(ndo, bp, length); } break; case ND_RPL_DAO: ND_PRINT((ndo, "Destination Advertisement Object")); if(ndo->ndo_vflag) { rpl_dao_print(ndo, bp, length); } break; case ND_RPL_DAO_ACK: ND_PRINT((ndo, "Destination Advertisement Object Ack")); if(ndo->ndo_vflag) { rpl_daoack_print(ndo, bp, length); } break; default: ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code)); break; } return; #if 0 trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; #endif }
169,832
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 DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); src.abort = true; return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; } Commit Message: CWE ID: CWE-20
void DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; }
165,394
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 mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) // we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size + 1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long UnserializeString(IMkvReader* pReader, long long pos, long long size, char*& str) { delete[] str; str = NULL; if (size >= LONG_MAX || size < 0) return E_FILE_FORMAT_INVALID; // +1 for '\0' terminator const long required_size = static_cast<long>(size) + 1; str = SafeArrayAlloc<char>(1, required_size); if (str == NULL) return E_FILE_FORMAT_INVALID; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[required_size - 1] = '\0'; return 0; }
173,867
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 RunSignBiasCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_output_block, 64); int count_sign_block[64][2]; const int count_test_block = 100000; memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = rnd.Rand8() - rnd.Rand8(); REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = 1125; EXPECT_LT(diff, max_diff) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-255, 255] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = (rnd.Rand8() >> 4) - (rnd.Rand8() >> 4); REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = 10000; EXPECT_LT(diff, max_diff) << "Error: 4x4 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-15, 15] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } } 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 RunSignBiasCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED(16, int16_t, test_input_block[64]); DECLARE_ALIGNED(16, tran_low_t, test_output_block[64]); int count_sign_block[64][2]; const int count_test_block = 100000; memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = ((rnd.Rand16() >> (16 - bit_depth_)) & mask_) - ((rnd.Rand16() >> (16 - bit_depth_)) & mask_); ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = kSignBiasMaxDiff255; EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-255, 255] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_ / 16, mask_ / 16]. for (int j = 0; j < 64; ++j) test_input_block[j] = ((rnd.Rand16() & mask_) >> 4) - ((rnd.Rand16() & mask_) >> 4); ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = kSignBiasMaxDiff15; EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-15, 15] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } }
174,561
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: BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { gd_error("Paletter image not supported by webp"); return; } if (quality == -1) { quality = 80; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); } Commit Message: Merge branch 'pull-request/296' CWE ID: CWE-190
BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { gd_error("Paletter image not supported by webp"); return; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); }
166,927
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(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,040
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 handle(int s, unsigned char* data, int len, struct sockaddr_in *s_in) { char buf[2048]; unsigned short *cmd = (unsigned short *)buf; int plen; struct in_addr *addr = &s_in->sin_addr; unsigned short *pid = (unsigned short*) data; /* inet check */ if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0) { unsigned short *id = (unsigned short*) (data+5); int x = 2+4+2; *cmd = htons(S_CMD_INET_CHECK); memcpy(cmd+1, addr, 4); memcpy(cmd+1+2, id, 2); printf("Inet check by %s %d\n", inet_ntoa(*addr), ntohs(*id)); if (send(s, buf, x, 0) != x) return 1; return 0; } *cmd++ = htons(S_CMD_PACKET); *cmd++ = *pid; plen = len - 2; last_id = ntohs(*pid); if (last_id > 20000) wrap = 1; if (wrap && last_id < 100) { wrap = 0; memset(ids, 0, sizeof(ids)); } printf("Got packet %d %d", last_id, plen); if (is_dup(last_id)) { printf(" (DUP)\n"); return 0; } printf("\n"); *cmd++ = htons(plen); memcpy(cmd, data+2, plen); plen += 2 + 2 + 2; assert(plen <= (int) sizeof(buf)); if (send(s, buf, plen, 0) != plen) return 1; return 0; } Commit Message: Buddy-ng: Fixed segmentation fault (Closes #15 on GitHub). git-svn-id: http://svn.aircrack-ng.org/trunk@2418 28c6078b-6c39-48e3-add9-af49d547ecab CWE ID: CWE-20
int handle(int s, unsigned char* data, int len, struct sockaddr_in *s_in) { char buf[2048]; unsigned short *cmd = (unsigned short *)buf; int plen; struct in_addr *addr = &s_in->sin_addr; unsigned short *pid = (unsigned short*) data; /* inet check */ if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0) { unsigned short *id = (unsigned short*) (data+5); int x = 2+4+2; *cmd = htons(S_CMD_INET_CHECK); memcpy(cmd+1, addr, 4); memcpy(cmd+1+2, id, 2); printf("Inet check by %s %d\n", inet_ntoa(*addr), ntohs(*id)); if (send(s, buf, x, 0) != x) return 1; return 0; } *cmd++ = htons(S_CMD_PACKET); *cmd++ = *pid; plen = len - 2; if (plen < 0) return 0; last_id = ntohs(*pid); if (last_id > 20000) wrap = 1; if (wrap && last_id < 100) { wrap = 0; memset(ids, 0, sizeof(ids)); } printf("Got packet %d %d", last_id, plen); if (is_dup(last_id)) { printf(" (DUP)\n"); return 0; } printf("\n"); *cmd++ = htons(plen); memcpy(cmd, data+2, plen); plen += 2 + 2 + 2; assert(plen <= (int) sizeof(buf)); if (send(s, buf, plen, 0) != plen) return 1; return 0; }
168,913
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: StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) { PersistentHistogramAllocator::GetCreateHistogramResultHistogram(); InitializeStatisticsRecorder(); if (use_persistent_histogram_allocator_) { GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "StatisticsRecorderTest"); } } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) { InitializeStatisticsRecorder(); if (use_persistent_histogram_allocator_) { GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "StatisticsRecorderTest"); } }
172,139
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 OMXNodeInstance::configureVideoTunnelMode( OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle) { Mutex::Autolock autolock(mLock); CLOG_CONFIG(configureVideoTunnelMode, "%s:%u tun=%d sync=%u", portString(portIndex), portIndex, tunneled, audioHwSync); OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.configureVideoTunnelMode"); OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err != OMX_ErrorNone) { CLOG_ERROR_IF(tunneled, getExtensionIndex, err, "%s", name); return StatusFromOMXError(err); } ConfigureVideoTunnelModeParams tunnelParams; InitOMXParams(&tunnelParams); tunnelParams.nPortIndex = portIndex; tunnelParams.bTunneled = tunneled; tunnelParams.nAudioHwSync = audioHwSync; err = OMX_SetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } err = OMX_GetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } if (sidebandHandle) { *sidebandHandle = (native_handle_t*)tunnelParams.pSidebandWindow; } return OK; } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::configureVideoTunnelMode( OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle) { Mutex::Autolock autolock(mLock); if (mSailed) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } CLOG_CONFIG(configureVideoTunnelMode, "%s:%u tun=%d sync=%u", portString(portIndex), portIndex, tunneled, audioHwSync); OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.configureVideoTunnelMode"); OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err != OMX_ErrorNone) { CLOG_ERROR_IF(tunneled, getExtensionIndex, err, "%s", name); return StatusFromOMXError(err); } ConfigureVideoTunnelModeParams tunnelParams; InitOMXParams(&tunnelParams); tunnelParams.nPortIndex = portIndex; tunnelParams.bTunneled = tunneled; tunnelParams.nAudioHwSync = audioHwSync; err = OMX_SetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } err = OMX_GetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } if (sidebandHandle) { *sidebandHandle = (native_handle_t*)tunnelParams.pSidebandWindow; } return OK; }
174,131
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 MSG_ReadBits( msg_t *msg, int bits ) { int value; int get; qboolean sgn; int i, nbits; value = 0; if ( bits < 0 ) { bits = -bits; sgn = qtrue; } else { sgn = qfalse; } if (msg->oob) { if(bits==8) { value = msg->data[msg->readcount]; msg->readcount += 1; msg->bit += 8; } else if(bits==16) { short temp; CopyLittleShort(&temp, &msg->data[msg->readcount]); value = temp; msg->readcount += 2; msg->bit += 16; } else if(bits==32) { CopyLittleLong(&value, &msg->data[msg->readcount]); msg->readcount += 4; msg->bit += 32; } else Com_Error(ERR_DROP, "can't read %d bits", bits); } else { nbits = 0; if (bits&7) { nbits = bits&7; for(i=0;i<nbits;i++) { value |= (Huff_getBit(msg->data, &msg->bit)<<i); } bits = bits - nbits; } if (bits) { for(i=0;i<bits;i+=8) { Huff_offsetReceive (msgHuff.decompressor.tree, &get, msg->data, &msg->bit); value |= (get<<(i+nbits)); } } msg->readcount = (msg->bit>>3)+1; } if ( sgn && bits > 0 && bits < 32 ) { if ( value & ( 1 << ( bits - 1 ) ) ) { value |= -1 ^ ( ( 1 << bits ) - 1 ); } } return value; } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
int MSG_ReadBits( msg_t *msg, int bits ) { int value; int get; qboolean sgn; int i, nbits; if ( msg->readcount > msg->cursize ) { return 0; } value = 0; if ( bits < 0 ) { bits = -bits; sgn = qtrue; } else { sgn = qfalse; } if (msg->oob) { if (msg->readcount + (bits>>3) > msg->cursize) { msg->readcount = msg->cursize + 1; return 0; } if(bits==8) { value = msg->data[msg->readcount]; msg->readcount += 1; msg->bit += 8; } else if(bits==16) { short temp; CopyLittleShort(&temp, &msg->data[msg->readcount]); value = temp; msg->readcount += 2; msg->bit += 16; } else if(bits==32) { CopyLittleLong(&value, &msg->data[msg->readcount]); msg->readcount += 4; msg->bit += 32; } else Com_Error(ERR_DROP, "can't read %d bits", bits); } else { nbits = 0; if (bits&7) { nbits = bits&7; if (msg->bit + nbits > msg->cursize << 3) { msg->readcount = msg->cursize + 1; return 0; } for(i=0;i<nbits;i++) { value |= (Huff_getBit(msg->data, &msg->bit)<<i); } bits = bits - nbits; } if (bits) { for(i=0;i<bits;i+=8) { Huff_offsetReceive (msgHuff.decompressor.tree, &get, msg->data, &msg->bit, msg->cursize<<3); value |= (get<<(i+nbits)); if (msg->bit > msg->cursize<<3) { msg->readcount = msg->cursize + 1; return 0; } } } msg->readcount = (msg->bit>>3)+1; } if ( sgn && bits > 0 && bits < 32 ) { if ( value & ( 1 << ( bits - 1 ) ) ) { value |= -1 ^ ( ( 1 << bits ) - 1 ); } } return value; }
167,998
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 AwContents::DidOverscroll(gfx::Vector2d overscroll_delta, gfx::Vector2dF overscroll_velocity) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(), overscroll_delta.y(), overscroll_velocity.x(), overscroll_velocity.y()); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta, void AwContents::DidOverscroll(const gfx::Vector2d& overscroll_delta, const gfx::Vector2dF& overscroll_velocity) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(), overscroll_delta.y(), overscroll_velocity.x(), overscroll_velocity.y()); }
171,616
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 g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width * 3, 16); aligned_height = FFALIGN(c->height, 16); av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; } Commit Message: avcodec/g2meet: Fix framebuf size Currently the code can in some cases draw tiles that hang outside the allocated buffer. This patch increases the buffer size to avoid out of array accesses. An alternative would be to fail if such tiles are encountered. I do not know if any valid files use such hanging tiles. Fixes Ticket2971 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3; aligned_height = c->height + 15; av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; }
165,915
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: CuePoint::~CuePoint() { delete[] m_track_positions; } 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
CuePoint::~CuePoint()
174,462
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 BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl() { element()->setFocus(true); } Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree. destroyShadowSubtree could dispatch 'blur' event unexpectedly because element()->focused() had incorrect information. We make sure it has correct information by checking if the UA shadow root contains the focused element. BUG=257353 Review URL: https://chromiumcodereview.appspot.com/19067004 git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl() { if (!containsFocusedShadowElement()) return; element()->setFocus(true); }
171,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: void SynchronousCompositorOutputSurface::InvokeComposite( const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, gfx::Transform transform_for_tile_priority, bool hardware_draw) { DCHECK(!frame_holder_.get()); gfx::Transform adjusted_transform = transform; adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0); SetExternalDrawConstraints(adjusted_transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, !hardware_draw); if (!hardware_draw || next_hardware_draw_needs_damage_) { next_hardware_draw_needs_damage_ = false; SetNeedsRedrawRect(gfx::Rect(viewport.size())); } client_->OnDraw(); if (hardware_draw) { cached_hw_transform_ = adjusted_transform; cached_hw_viewport_ = viewport; cached_hw_clip_ = clip; cached_hw_viewport_rect_for_tile_priority_ = viewport_rect_for_tile_priority; cached_hw_transform_for_tile_priority_ = transform_for_tile_priority; } else { bool resourceless_software_draw = false; SetExternalDrawConstraints(cached_hw_transform_, cached_hw_viewport_, cached_hw_clip_, cached_hw_viewport_rect_for_tile_priority_, cached_hw_transform_for_tile_priority_, resourceless_software_draw); next_hardware_draw_needs_damage_ = true; } if (frame_holder_.get()) client_->DidSwapBuffersComplete(); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void SynchronousCompositorOutputSurface::InvokeComposite( const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority, bool hardware_draw) { DCHECK(!frame_holder_.get()); gfx::Transform adjusted_transform = transform; adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0); SetExternalDrawConstraints(adjusted_transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, !hardware_draw); if (!hardware_draw || next_hardware_draw_needs_damage_) { next_hardware_draw_needs_damage_ = false; SetNeedsRedrawRect(gfx::Rect(viewport.size())); } client_->OnDraw(); if (hardware_draw) { cached_hw_transform_ = adjusted_transform; cached_hw_viewport_ = viewport; cached_hw_clip_ = clip; cached_hw_viewport_rect_for_tile_priority_ = viewport_rect_for_tile_priority; cached_hw_transform_for_tile_priority_ = transform_for_tile_priority; } else { bool resourceless_software_draw = false; SetExternalDrawConstraints(cached_hw_transform_, cached_hw_viewport_, cached_hw_clip_, cached_hw_viewport_rect_for_tile_priority_, cached_hw_transform_for_tile_priority_, resourceless_software_draw); next_hardware_draw_needs_damage_ = true; } if (frame_holder_.get()) client_->DidSwapBuffersComplete(); }
171,622
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 ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } return 0; }
173,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: file_add_mapi_attrs (File* file, MAPI_Attr** attrs) { int i; for (i = 0; attrs[i]; i++) { MAPI_Attr* a = attrs[i]; if (a->num_values) { switch (a->name) { case MAPI_ATTACH_LONG_FILENAME: if (file->name) XFREE(file->name); file->name = strdup( (char*)a->values[0].data.buf ); break; case MAPI_ATTACH_DATA_OBJ: file->len = a->values[0].len; if (file->data) XFREE (file->data); file->data = CHECKED_XMALLOC (unsigned char, file->len); memmove (file->data, a->values[0].data.buf, file->len); break; case MAPI_ATTACH_MIME_TAG: if (file->mime_type) XFREE (file->mime_type); file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); break; case MAPI_ATTACH_CONTENT_ID: if (file->content_id) XFREE(file->content_id); file->content_id = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->content_id, a->values[0].data.buf, a->values[0].len); break; default: break; } } } } Commit Message: Check types to avoid invalid reads/writes. CWE ID: CWE-125
file_add_mapi_attrs (File* file, MAPI_Attr** attrs) { int i; for (i = 0; attrs[i]; i++) { MAPI_Attr* a = attrs[i]; if (a->num_values) { switch (a->name) { case MAPI_ATTACH_LONG_FILENAME: assert(a->type == szMAPI_STRING); if (file->name) XFREE(file->name); file->name = strdup( (char*)a->values[0].data.buf ); break; case MAPI_ATTACH_DATA_OBJ: assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT)); file->len = a->values[0].len; if (file->data) XFREE (file->data); file->data = CHECKED_XMALLOC (unsigned char, file->len); memmove (file->data, a->values[0].data.buf, file->len); break; case MAPI_ATTACH_MIME_TAG: assert(a->type == szMAPI_STRING); if (file->mime_type) XFREE (file->mime_type); file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); break; case MAPI_ATTACH_CONTENT_ID: assert(a->type == szMAPI_STRING); if (file->content_id) XFREE(file->content_id); file->content_id = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->content_id, a->values[0].data.buf, a->values[0].len); break; default: break; } } } }
168,351
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 init_vmcb(struct vcpu_svm *svm) { struct vmcb_control_area *control = &svm->vmcb->control; struct vmcb_save_area *save = &svm->vmcb->save; svm->vcpu.fpu_active = 1; svm->vcpu.arch.hflags = 0; set_cr_intercept(svm, INTERCEPT_CR0_READ); set_cr_intercept(svm, INTERCEPT_CR3_READ); set_cr_intercept(svm, INTERCEPT_CR4_READ); set_cr_intercept(svm, INTERCEPT_CR0_WRITE); set_cr_intercept(svm, INTERCEPT_CR3_WRITE); set_cr_intercept(svm, INTERCEPT_CR4_WRITE); set_cr_intercept(svm, INTERCEPT_CR8_WRITE); set_dr_intercepts(svm); set_exception_intercept(svm, PF_VECTOR); set_exception_intercept(svm, UD_VECTOR); set_exception_intercept(svm, MC_VECTOR); set_intercept(svm, INTERCEPT_INTR); set_intercept(svm, INTERCEPT_NMI); set_intercept(svm, INTERCEPT_SMI); set_intercept(svm, INTERCEPT_SELECTIVE_CR0); set_intercept(svm, INTERCEPT_RDPMC); set_intercept(svm, INTERCEPT_CPUID); set_intercept(svm, INTERCEPT_INVD); set_intercept(svm, INTERCEPT_HLT); set_intercept(svm, INTERCEPT_INVLPG); set_intercept(svm, INTERCEPT_INVLPGA); set_intercept(svm, INTERCEPT_IOIO_PROT); set_intercept(svm, INTERCEPT_MSR_PROT); set_intercept(svm, INTERCEPT_TASK_SWITCH); set_intercept(svm, INTERCEPT_SHUTDOWN); set_intercept(svm, INTERCEPT_VMRUN); set_intercept(svm, INTERCEPT_VMMCALL); set_intercept(svm, INTERCEPT_VMLOAD); set_intercept(svm, INTERCEPT_VMSAVE); set_intercept(svm, INTERCEPT_STGI); set_intercept(svm, INTERCEPT_CLGI); set_intercept(svm, INTERCEPT_SKINIT); set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); set_intercept(svm, INTERCEPT_XSETBV); control->iopm_base_pa = iopm_base; control->msrpm_base_pa = __pa(svm->msrpm); control->int_ctl = V_INTR_MASKING_MASK; init_seg(&save->es); init_seg(&save->ss); init_seg(&save->ds); init_seg(&save->fs); init_seg(&save->gs); save->cs.selector = 0xf000; save->cs.base = 0xffff0000; /* Executable/Readable Code Segment */ save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; save->cs.limit = 0xffff; save->gdtr.limit = 0xffff; save->idtr.limit = 0xffff; init_sys_seg(&save->ldtr, SEG_TYPE_LDT); init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); svm_set_efer(&svm->vcpu, 0); save->dr6 = 0xffff0ff0; kvm_set_rflags(&svm->vcpu, 2); save->rip = 0x0000fff0; svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; /* * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. * It also updates the guest-visible cr0 value. */ svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); kvm_mmu_reset_context(&svm->vcpu); save->cr4 = X86_CR4_PAE; /* rdx = ?? */ if (npt_enabled) { /* Setup VMCB for Nested Paging */ control->nested_ctl = 1; clr_intercept(svm, INTERCEPT_INVLPG); clr_exception_intercept(svm, PF_VECTOR); clr_cr_intercept(svm, INTERCEPT_CR3_READ); clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); save->g_pat = svm->vcpu.arch.pat; save->cr3 = 0; save->cr4 = 0; } svm->asid_generation = 0; svm->nested.vmcb = 0; svm->vcpu.arch.hflags = 0; if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { control->pause_filter_count = 3000; set_intercept(svm, INTERCEPT_PAUSE); } mark_all_dirty(svm->vmcb); enable_gif(svm); } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399
static void init_vmcb(struct vcpu_svm *svm) { struct vmcb_control_area *control = &svm->vmcb->control; struct vmcb_save_area *save = &svm->vmcb->save; svm->vcpu.fpu_active = 1; svm->vcpu.arch.hflags = 0; set_cr_intercept(svm, INTERCEPT_CR0_READ); set_cr_intercept(svm, INTERCEPT_CR3_READ); set_cr_intercept(svm, INTERCEPT_CR4_READ); set_cr_intercept(svm, INTERCEPT_CR0_WRITE); set_cr_intercept(svm, INTERCEPT_CR3_WRITE); set_cr_intercept(svm, INTERCEPT_CR4_WRITE); set_cr_intercept(svm, INTERCEPT_CR8_WRITE); set_dr_intercepts(svm); set_exception_intercept(svm, PF_VECTOR); set_exception_intercept(svm, UD_VECTOR); set_exception_intercept(svm, MC_VECTOR); set_exception_intercept(svm, AC_VECTOR); set_intercept(svm, INTERCEPT_INTR); set_intercept(svm, INTERCEPT_NMI); set_intercept(svm, INTERCEPT_SMI); set_intercept(svm, INTERCEPT_SELECTIVE_CR0); set_intercept(svm, INTERCEPT_RDPMC); set_intercept(svm, INTERCEPT_CPUID); set_intercept(svm, INTERCEPT_INVD); set_intercept(svm, INTERCEPT_HLT); set_intercept(svm, INTERCEPT_INVLPG); set_intercept(svm, INTERCEPT_INVLPGA); set_intercept(svm, INTERCEPT_IOIO_PROT); set_intercept(svm, INTERCEPT_MSR_PROT); set_intercept(svm, INTERCEPT_TASK_SWITCH); set_intercept(svm, INTERCEPT_SHUTDOWN); set_intercept(svm, INTERCEPT_VMRUN); set_intercept(svm, INTERCEPT_VMMCALL); set_intercept(svm, INTERCEPT_VMLOAD); set_intercept(svm, INTERCEPT_VMSAVE); set_intercept(svm, INTERCEPT_STGI); set_intercept(svm, INTERCEPT_CLGI); set_intercept(svm, INTERCEPT_SKINIT); set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); set_intercept(svm, INTERCEPT_XSETBV); control->iopm_base_pa = iopm_base; control->msrpm_base_pa = __pa(svm->msrpm); control->int_ctl = V_INTR_MASKING_MASK; init_seg(&save->es); init_seg(&save->ss); init_seg(&save->ds); init_seg(&save->fs); init_seg(&save->gs); save->cs.selector = 0xf000; save->cs.base = 0xffff0000; /* Executable/Readable Code Segment */ save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; save->cs.limit = 0xffff; save->gdtr.limit = 0xffff; save->idtr.limit = 0xffff; init_sys_seg(&save->ldtr, SEG_TYPE_LDT); init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); svm_set_efer(&svm->vcpu, 0); save->dr6 = 0xffff0ff0; kvm_set_rflags(&svm->vcpu, 2); save->rip = 0x0000fff0; svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; /* * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. * It also updates the guest-visible cr0 value. */ svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); kvm_mmu_reset_context(&svm->vcpu); save->cr4 = X86_CR4_PAE; /* rdx = ?? */ if (npt_enabled) { /* Setup VMCB for Nested Paging */ control->nested_ctl = 1; clr_intercept(svm, INTERCEPT_INVLPG); clr_exception_intercept(svm, PF_VECTOR); clr_cr_intercept(svm, INTERCEPT_CR3_READ); clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); save->g_pat = svm->vcpu.arch.pat; save->cr3 = 0; save->cr4 = 0; } svm->asid_generation = 0; svm->nested.vmcb = 0; svm->vcpu.arch.hflags = 0; if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { control->pause_filter_count = 3000; set_intercept(svm, INTERCEPT_PAUSE); } mark_all_dirty(svm->vmcb); enable_gif(svm); }
166,598
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: key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (!ctx.match_data.cmp) return ERR_PTR(-ENOKEY); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476
key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; }
168,440
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 noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; else if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; } switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } } Commit Message: HID: hiddev: validate num_values for HIDIOCGUSAGES, HIDIOCSUSAGES commands This patch validates the num_values parameter from userland during the HIDIOCGUSAGES and HIDIOCSUSAGES commands. Previously, if the report id was set to HID_REPORT_ID_UNKNOWN, we would fail to validate the num_values parameter leading to a heap overflow. Cc: [email protected] Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; } if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } }
167,022
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: vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct vqp_common_header_t *vqp_common_header; const struct vqp_obj_tlv_t *vqp_obj_tlv; const u_char *tptr; uint16_t vqp_obj_len; uint32_t vqp_obj_type; int tlen; uint8_t nitems; tptr=pptr; tlen = len; vqp_common_header = (const struct vqp_common_header_t *)pptr; ND_TCHECK(*vqp_common_header); /* * Sanity checking of the header. */ if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) { ND_PRINT((ndo, "VQP version %u packet not supported", VQP_EXTRACT_VERSION(vqp_common_header->version))); return; } /* in non-verbose mode just lets print the basic Message Type */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, len)); return; } /* ok they seem to want to know everything - lets fully decode it */ nitems = vqp_common_header->nitems; ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, EXTRACT_32BITS(&vqp_common_header->sequence), nitems, len)); /* skip VQP Common header */ tptr+=sizeof(const struct vqp_common_header_t); tlen-=sizeof(const struct vqp_common_header_t); while (nitems > 0 && tlen > 0) { vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr; vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type); vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length); tptr+=sizeof(struct vqp_obj_tlv_t); tlen-=sizeof(struct vqp_obj_tlv_t); ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ", tok2str(vqp_obj_values, "Unknown", vqp_obj_type), vqp_obj_type, vqp_obj_len)); /* basic sanity check */ if (vqp_obj_type == 0 || vqp_obj_len ==0) { return; } /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, vqp_obj_len); switch(vqp_obj_type) { case VQP_OBJ_IP_ADDRESS: ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr))); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_PORT_NAME: case VQP_OBJ_VLAN_NAME: case VQP_OBJ_VTP_DOMAIN: case VQP_OBJ_ETHERNET_PKT: safeputs(ndo, tptr, vqp_obj_len); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_MAC_ADDRESS: case VQP_OBJ_MAC_NULL: ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr))); break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len); break; } tptr += vqp_obj_len; tlen -= vqp_obj_len; nitems--; } return; trunc: ND_PRINT((ndo, "\n\t[|VQP]")); } Commit Message: CVE-2017-13045/VQP: add some bounds checks 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
vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct vqp_common_header_t *vqp_common_header; const struct vqp_obj_tlv_t *vqp_obj_tlv; const u_char *tptr; uint16_t vqp_obj_len; uint32_t vqp_obj_type; u_int tlen; uint8_t nitems; tptr=pptr; tlen = len; vqp_common_header = (const struct vqp_common_header_t *)pptr; ND_TCHECK(*vqp_common_header); if (sizeof(struct vqp_common_header_t) > tlen) goto trunc; /* * Sanity checking of the header. */ if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) { ND_PRINT((ndo, "VQP version %u packet not supported", VQP_EXTRACT_VERSION(vqp_common_header->version))); return; } /* in non-verbose mode just lets print the basic Message Type */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, len)); return; } /* ok they seem to want to know everything - lets fully decode it */ nitems = vqp_common_header->nitems; ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, EXTRACT_32BITS(&vqp_common_header->sequence), nitems, len)); /* skip VQP Common header */ tptr+=sizeof(const struct vqp_common_header_t); tlen-=sizeof(const struct vqp_common_header_t); while (nitems > 0 && tlen > 0) { vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr; ND_TCHECK(*vqp_obj_tlv); if (sizeof(struct vqp_obj_tlv_t) > tlen) goto trunc; vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type); vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length); tptr+=sizeof(struct vqp_obj_tlv_t); tlen-=sizeof(struct vqp_obj_tlv_t); ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ", tok2str(vqp_obj_values, "Unknown", vqp_obj_type), vqp_obj_type, vqp_obj_len)); /* basic sanity check */ if (vqp_obj_type == 0 || vqp_obj_len ==0) { return; } /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, vqp_obj_len); if (vqp_obj_len > tlen) goto trunc; switch(vqp_obj_type) { case VQP_OBJ_IP_ADDRESS: if (vqp_obj_len != 4) goto trunc; ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr))); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_PORT_NAME: case VQP_OBJ_VLAN_NAME: case VQP_OBJ_VTP_DOMAIN: case VQP_OBJ_ETHERNET_PKT: safeputs(ndo, tptr, vqp_obj_len); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_MAC_ADDRESS: case VQP_OBJ_MAC_NULL: if (vqp_obj_len != ETHER_ADDR_LEN) goto trunc; ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr))); break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len); break; } tptr += vqp_obj_len; tlen -= vqp_obj_len; nitems--; } return; trunc: ND_PRINT((ndo, "\n\t[|VQP]")); }
167,830
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: XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetOutputInfoReply rep; xRRGetOutputInfoReq *req; int nbytes, nbytesRead, rbytes; XRROutputInfo *xoi; RRCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (RRGetOutputInfo, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetOutputInfo; req->output = output; req->configTimestamp = resources->configTimestamp; if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; return NULL; } nbytes = ((long) (rep.length) << 2) - OutputInfoExtra; nbytesRead = (long) (rep.nCrtcs * 4 + rep.nCrtcs * sizeof (RRCrtc) + rep.nModes * sizeof (RRMode) + rep.nClones * sizeof (RROutput) + rep.nameLength + 1); /* '\0' terminate name */ xoi = (XRROutputInfo *) Xmalloc(rbytes); if (xoi == NULL) { _XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2)); UnlockDisplay (dpy); SyncHandle (); return NULL; } xoi->timestamp = rep.timestamp; xoi->crtc = rep.crtc; xoi->mm_width = rep.mmWidth; xoi->mm_height = rep.mmHeight; xoi->connection = rep.connection; xoi->subpixel_order = rep.subpixelOrder; xoi->ncrtc = rep.nCrtcs; xoi->crtcs = (RRCrtc *) (xoi + 1); xoi->nmode = rep.nModes; xoi->npreferred = rep.nPreferred; xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs); xoi->nclone = rep.nClones; xoi->clones = (RROutput *) (xoi->modes + rep.nModes); xoi->name = (char *) (xoi->clones + rep.nClones); _XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2); _XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2); _XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2); /* * Read name and '\0' terminate */ _XReadPad (dpy, xoi->name, rep.nameLength); xoi->name[rep.nameLength] = '\0'; xoi->nameLen = rep.nameLength; /* * Skip any extra data */ if (nbytes > nbytesRead) _XEatData (dpy, (unsigned long) (nbytes - nbytesRead)); UnlockDisplay (dpy); SyncHandle (); return (XRROutputInfo *) xoi; } Commit Message: CWE ID: CWE-787
XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetOutputInfoReply rep; xRRGetOutputInfoReq *req; int nbytes, nbytesRead, rbytes; XRROutputInfo *xoi; RRCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (RRGetOutputInfo, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetOutputInfo; req->output = output; req->configTimestamp = resources->configTimestamp; if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; return NULL; } if (rep.length > INT_MAX >> 2 || rep.length < (OutputInfoExtra >> 2)) { if (rep.length > (OutputInfoExtra >> 2)) _XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2)); else _XEatDataWords (dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return NULL; } nbytes = ((long) (rep.length) << 2) - OutputInfoExtra; nbytesRead = (long) (rep.nCrtcs * 4 + rep.nCrtcs * sizeof (RRCrtc) + rep.nModes * sizeof (RRMode) + rep.nClones * sizeof (RROutput) + rep.nameLength + 1); /* '\0' terminate name */ xoi = (XRROutputInfo *) Xmalloc(rbytes); if (xoi == NULL) { _XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2)); UnlockDisplay (dpy); SyncHandle (); return NULL; } xoi->timestamp = rep.timestamp; xoi->crtc = rep.crtc; xoi->mm_width = rep.mmWidth; xoi->mm_height = rep.mmHeight; xoi->connection = rep.connection; xoi->subpixel_order = rep.subpixelOrder; xoi->ncrtc = rep.nCrtcs; xoi->crtcs = (RRCrtc *) (xoi + 1); xoi->nmode = rep.nModes; xoi->npreferred = rep.nPreferred; xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs); xoi->nclone = rep.nClones; xoi->clones = (RROutput *) (xoi->modes + rep.nModes); xoi->name = (char *) (xoi->clones + rep.nClones); _XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2); _XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2); _XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2); /* * Read name and '\0' terminate */ _XReadPad (dpy, xoi->name, rep.nameLength); xoi->name[rep.nameLength] = '\0'; xoi->nameLen = rep.nameLength; /* * Skip any extra data */ if (nbytes > nbytesRead) _XEatData (dpy, (unsigned long) (nbytes - nbytesRead)); UnlockDisplay (dpy); SyncHandle (); return (XRROutputInfo *) xoi; }
164,915
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 php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; } Commit Message: CWE ID: CWE-20
static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; }
165,479
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 HTMLFormElement::scheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod); DCHECK(submission->data()); DCHECK(submission->form()); if (submission->action().isEmpty()) return; if (document().isSandboxed(SandboxForms)) { document().addConsoleMessage(ConsoleMessage::create( SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (protocolIsJavaScript(submission->action())) { if (!document().contentSecurityPolicy()->allowFormAction( submission->action())) return; document().frame()->script().executeScriptIfJavaScriptURL( submission->action(), this); return; } Frame* targetFrame = document().frame()->findFrameForNavigation( submission->target(), *document().frame()); if (!targetFrame) { if (!LocalDOMWindow::allowPopUp(*document().frame()) && !UserGestureIndicator::utilizeUserGesture()) return; targetFrame = document().frame(); } else { submission->clearTarget(); } if (!targetFrame->host()) return; UseCounter::count(document(), UseCounter::FormsSubmitted); if (MixedContentChecker::isMixedFormAction(document().frame(), submission->action())) UseCounter::count(document().frame(), UseCounter::MixedContentFormsSubmitted); if (targetFrame->isLocalFrame()) { toLocalFrame(targetFrame) ->navigationScheduler() .scheduleFormSubmission(&document(), submission); } else { FrameLoadRequest frameLoadRequest = submission->createFrameLoadRequest(&document()); toRemoteFrame(targetFrame)->navigate(frameLoadRequest); } } Commit Message: Enforce form-action CSP even when form.target is present. BUG=630332 Review-Url: https://codereview.chromium.org/2464123004 Cr-Commit-Position: refs/heads/master@{#429922} CWE ID: CWE-19
void HTMLFormElement::scheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod); DCHECK(submission->data()); DCHECK(submission->form()); if (submission->action().isEmpty()) return; if (document().isSandboxed(SandboxForms)) { document().addConsoleMessage(ConsoleMessage::create( SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!document().contentSecurityPolicy()->allowFormAction( submission->action())) { return; } if (protocolIsJavaScript(submission->action())) { document().frame()->script().executeScriptIfJavaScriptURL( submission->action(), this); return; } Frame* targetFrame = document().frame()->findFrameForNavigation( submission->target(), *document().frame()); if (!targetFrame) { if (!LocalDOMWindow::allowPopUp(*document().frame()) && !UserGestureIndicator::utilizeUserGesture()) return; targetFrame = document().frame(); } else { submission->clearTarget(); } if (!targetFrame->host()) return; UseCounter::count(document(), UseCounter::FormsSubmitted); if (MixedContentChecker::isMixedFormAction(document().frame(), submission->action())) UseCounter::count(document().frame(), UseCounter::MixedContentFormsSubmitted); if (targetFrame->isLocalFrame()) { toLocalFrame(targetFrame) ->navigationScheduler() .scheduleFormSubmission(&document(), submission); } else { FrameLoadRequest frameLoadRequest = submission->createFrameLoadRequest(&document()); toRemoteFrame(targetFrame)->navigate(frameLoadRequest); } }
172,545
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: decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; }
169,072
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 BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { DictionaryValue params; params.SetString("pairing", "bluetoothEnterPasskey"); SendDeviceNotification(device, &params); }
170,972
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 RecordResourceCompletionUMA(bool image_complete, bool css_complete, bool xhr_complete) { base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Image", image_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Css", css_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Xhr", xhr_complete); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
void RecordResourceCompletionUMA(bool image_complete,
172,483
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 serdes_probe(struct platform_device *pdev) { struct phy_provider *provider; struct serdes_ctrl *ctrl; unsigned int i; int ret; ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return -ENOMEM; ctrl->dev = &pdev->dev; ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(ctrl->regs)) return PTR_ERR(ctrl->regs); for (i = 0; i <= SERDES_MAX; i++) { ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]); if (ret) return ret; } dev_set_drvdata(&pdev->dev, ctrl); provider = devm_of_phy_provider_register(ctrl->dev, serdes_simple_xlate); return PTR_ERR_OR_ZERO(provider); } Commit Message: phy: ocelot-serdes: fix out-of-bounds read Currently, there is an out-of-bounds read on array ctrl->phys, once variable i reaches the maximum array size of SERDES_MAX in the for loop. Fix this by changing the condition in the for loop from i <= SERDES_MAX to i < SERDES_MAX. Addresses-Coverity-ID: 1473966 ("Out-of-bounds read") Addresses-Coverity-ID: 1473959 ("Out-of-bounds read") Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing") Reviewed-by: Quentin Schulz <[email protected]> Signed-off-by: Gustavo A. R. Silva <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
static int serdes_probe(struct platform_device *pdev) { struct phy_provider *provider; struct serdes_ctrl *ctrl; unsigned int i; int ret; ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return -ENOMEM; ctrl->dev = &pdev->dev; ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(ctrl->regs)) return PTR_ERR(ctrl->regs); for (i = 0; i < SERDES_MAX; i++) { ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]); if (ret) return ret; } dev_set_drvdata(&pdev->dev, ctrl); provider = devm_of_phy_provider_register(ctrl->dev, serdes_simple_xlate); return PTR_ERR_OR_ZERO(provider); }
169,764
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 unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned* lengths; unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned)); if (!lengths) free(tree->lengths); tree->lengths = lengths; if(!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; }
169,499
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 MSG_WriteBits( msg_t *msg, int value, int bits ) { int i; oldsize += bits; if ( msg->maxsize - msg->cursize < 4 ) { msg->overflowed = qtrue; return; } if ( bits == 0 || bits < -31 || bits > 32 ) { Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); } if ( bits < 0 ) { bits = -bits; } if ( msg->oob ) { if ( bits == 8 ) { msg->data[msg->cursize] = value; msg->cursize += 1; msg->bit += 8; } else if ( bits == 16 ) { short temp = value; CopyLittleShort( &msg->data[msg->cursize], &temp ); msg->cursize += 2; msg->bit += 16; } else if ( bits==32 ) { CopyLittleLong( &msg->data[msg->cursize], &value ); msg->cursize += 4; msg->bit += 32; } else { Com_Error( ERR_DROP, "can't write %d bits", bits ); } } else { value &= (0xffffffff >> (32 - bits)); if ( bits&7 ) { int nbits; nbits = bits&7; for( i = 0; i < nbits; i++ ) { Huff_putBit( (value & 1), msg->data, &msg->bit ); value = (value >> 1); } bits = bits - nbits; } if ( bits ) { for( i = 0; i < bits; i += 8 ) { Huff_offsetTransmit( &msgHuff.compressor, (value & 0xff), msg->data, &msg->bit ); value = (value >> 8); } } msg->cursize = (msg->bit >> 3) + 1; } } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
void MSG_WriteBits( msg_t *msg, int value, int bits ) { int i; oldsize += bits; if ( msg->overflowed ) { return; } if ( bits == 0 || bits < -31 || bits > 32 ) { Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); } if ( bits < 0 ) { bits = -bits; } if ( msg->oob ) { if ( msg->cursize + ( bits >> 3 ) > msg->maxsize ) { msg->overflowed = qtrue; return; } if ( bits == 8 ) { msg->data[msg->cursize] = value; msg->cursize += 1; msg->bit += 8; } else if ( bits == 16 ) { short temp = value; CopyLittleShort( &msg->data[msg->cursize], &temp ); msg->cursize += 2; msg->bit += 16; } else if ( bits==32 ) { CopyLittleLong( &msg->data[msg->cursize], &value ); msg->cursize += 4; msg->bit += 32; } else { Com_Error( ERR_DROP, "can't write %d bits", bits ); } } else { value &= (0xffffffff >> (32 - bits)); if ( bits&7 ) { int nbits; nbits = bits&7; if ( msg->bit + nbits > msg->maxsize << 3 ) { msg->overflowed = qtrue; return; } for( i = 0; i < nbits; i++ ) { Huff_putBit( (value & 1), msg->data, &msg->bit ); value = (value >> 1); } bits = bits - nbits; } if ( bits ) { for( i = 0; i < bits; i += 8 ) { Huff_offsetTransmit( &msgHuff.compressor, (value & 0xff), msg->data, &msg->bit, msg->maxsize << 3 ); value = (value >> 8); if ( msg->bit > msg->maxsize << 3 ) { msg->overflowed = qtrue; return; } } } msg->cursize = (msg->bit >> 3) + 1; } }
167,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: unsigned int subpel_avg_variance_ref(const uint8_t *ref, const uint8_t *src, const uint8_t *second_pred, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } 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
unsigned int subpel_avg_variance_ref(const uint8_t *ref,
174,594
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 SoftAMRWBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeWB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeWB8) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = (VOAMRWBMODE)( amrParams->eAMRBandMode - OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (VO_ERR_NONE != mApiHandle->SetParam( mEncoderHandle, VO_PID_AMRWB_MODE, &mMode)) { ALOGE("Failed to set AMRWB encoder mode to %d", mMode); return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMRWBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeWB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeWB8) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = (VOAMRWBMODE)( amrParams->eAMRBandMode - OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (VO_ERR_NONE != mApiHandle->SetParam( mEncoderHandle, VO_PID_AMRWB_MODE, &mMode)) { ALOGE("Failed to set AMRWB encoder mode to %d", mMode); return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,197
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: xsltNumberFormatAlpha(xmlBufferPtr buffer, double number, int is_upper) { char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1]; char *pointer; int i; char *alpha_list; double alpha_size = (double)(sizeof(alpha_upper_list) - 1); /* Build buffer from back */ pointer = &temp_string[sizeof(temp_string)]; *(--pointer) = 0; alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list; for (i = 1; i < (int)sizeof(temp_string); i++) { number--; *(--pointer) = alpha_list[((int)fmod(number, alpha_size))]; number /= alpha_size; if (fabs(number) < 1.0) break; /* for */ } xmlBufferCCat(buffer, pointer); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltNumberFormatAlpha(xmlBufferPtr buffer, double number, int is_upper) { char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1]; char *pointer; int i; char *alpha_list; double alpha_size = (double)(sizeof(alpha_upper_list) - 1); if (number < 1.0) return; /* Build buffer from back */ pointer = &temp_string[sizeof(temp_string)]; *(--pointer) = 0; alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list; for (i = 1; i < (int)sizeof(temp_string); i++) { number--; *(--pointer) = alpha_list[((int)fmod(number, alpha_size))]; number /= alpha_size; if (number < 1.0) break; /* for */ } xmlBufferCCat(buffer, pointer); }
173,307
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 VideoTrack::GetHeight() const { return m_height; } 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 VideoTrack::GetHeight() const
174,327
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 SegmentInfo::GetDuration() const { if (m_duration < 0) return -1; assert(m_timecodeScale >= 1); const double dd = double(m_duration) * double(m_timecodeScale); const long long d = static_cast<long long>(dd); return d; } 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 SegmentInfo::GetDuration() const
174,307
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 DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, renderer_process_, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); } 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:
void DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); }
170,941
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 read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) { if (pkt->size >= 7 && pkt->size < INT_MAX - AVPROBE_PADDING_SIZE && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) { uint8_t desc[256]; int score = AVPROBE_SCORE_EXTENSION, ret; AVIStream *ast = st->priv_data; AVInputFormat *sub_demuxer; AVRational time_base; int size; AVIOContext *pb = avio_alloc_context(pkt->data + 7, pkt->size - 7, 0, NULL, NULL, NULL, NULL); AVProbeData pd; unsigned int desc_len = avio_rl32(pb); if (desc_len > pb->buf_end - pb->buf_ptr) goto error; ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc)); avio_skip(pb, desc_len - ret); if (*desc) av_dict_set(&st->metadata, "title", desc, 0); avio_rl16(pb); /* flags? */ avio_rl32(pb); /* data size */ size = pb->buf_end - pb->buf_ptr; pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE), .buf_size = size }; if (!pd.buf) goto error; memcpy(pd.buf, pb->buf_ptr, size); sub_demuxer = av_probe_input_format2(&pd, 1, &score); av_freep(&pd.buf); if (!sub_demuxer) goto error; if (!(ast->sub_ctx = avformat_alloc_context())) goto error; ast->sub_ctx->pb = pb; if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0) goto error; if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) { if (ast->sub_ctx->nb_streams != 1) goto error; ff_read_packet(ast->sub_ctx, &ast->sub_pkt); avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar); time_base = ast->sub_ctx->streams[0]->time_base; avpriv_set_pts_info(st, 64, time_base.num, time_base.den); } ast->sub_buffer = pkt->data; memset(pkt, 0, sizeof(*pkt)); return 1; error: av_freep(&ast->sub_ctx); av_freep(&pb); } return 0; } Commit Message: avformat/avidec: Limit formats in gab2 to srt and ass/ssa This prevents part of one exploit leading to an information leak Found-by: Emil Lerner and Pavel Cheremushkin Reported-by: Thierry Foucu <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-200
static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) { if (pkt->size >= 7 && pkt->size < INT_MAX - AVPROBE_PADDING_SIZE && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) { uint8_t desc[256]; int score = AVPROBE_SCORE_EXTENSION, ret; AVIStream *ast = st->priv_data; AVInputFormat *sub_demuxer; AVRational time_base; int size; AVIOContext *pb = avio_alloc_context(pkt->data + 7, pkt->size - 7, 0, NULL, NULL, NULL, NULL); AVProbeData pd; unsigned int desc_len = avio_rl32(pb); if (desc_len > pb->buf_end - pb->buf_ptr) goto error; ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc)); avio_skip(pb, desc_len - ret); if (*desc) av_dict_set(&st->metadata, "title", desc, 0); avio_rl16(pb); /* flags? */ avio_rl32(pb); /* data size */ size = pb->buf_end - pb->buf_ptr; pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE), .buf_size = size }; if (!pd.buf) goto error; memcpy(pd.buf, pb->buf_ptr, size); sub_demuxer = av_probe_input_format2(&pd, 1, &score); av_freep(&pd.buf); if (!sub_demuxer) goto error; if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass")) goto error; if (!(ast->sub_ctx = avformat_alloc_context())) goto error; ast->sub_ctx->pb = pb; if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0) goto error; if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) { if (ast->sub_ctx->nb_streams != 1) goto error; ff_read_packet(ast->sub_ctx, &ast->sub_pkt); avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar); time_base = ast->sub_ctx->streams[0]->time_base; avpriv_set_pts_info(st, 64, time_base.num, time_base.den); } ast->sub_buffer = pkt->data; memset(pkt, 0, sizeof(*pkt)); return 1; error: av_freep(&ast->sub_ctx); av_freep(&pb); } return 0; }
168,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: DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient( const net::BackoffEntry::Policy& backoff_policy, DataReductionProxyRequestOptions* request_options, DataReductionProxyMutableConfigValues* config_values, DataReductionProxyConfig* config, DataReductionProxyIOData* io_data, network::NetworkConnectionTracker* network_connection_tracker, ConfigStorer config_storer) : request_options_(request_options), config_values_(config_values), config_(config), io_data_(io_data), network_connection_tracker_(network_connection_tracker), config_storer_(config_storer), backoff_policy_(backoff_policy), backoff_entry_(&backoff_policy_), config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())), enabled_(false), remote_config_applied_(false), #if defined(OS_ANDROID) foreground_fetch_pending_(false), #endif previous_request_failed_authentication_(false), failed_attempts_before_success_(0), fetch_in_progress_(false), client_config_override_used_(false) { DCHECK(request_options); DCHECK(config_values); DCHECK(config); DCHECK(io_data); DCHECK(config_service_url_.is_valid()); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); client_config_override_ = command_line.GetSwitchValueASCII( switches::kDataReductionProxyServerClientConfig); thread_checker_.DetachFromThread(); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient( const net::BackoffEntry::Policy& backoff_policy, DataReductionProxyRequestOptions* request_options, DataReductionProxyMutableConfigValues* config_values, DataReductionProxyConfig* config, DataReductionProxyIOData* io_data, network::NetworkConnectionTracker* network_connection_tracker, ConfigStorer config_storer) : request_options_(request_options), config_values_(config_values), config_(config), io_data_(io_data), network_connection_tracker_(network_connection_tracker), config_storer_(config_storer), backoff_policy_(backoff_policy), backoff_entry_(&backoff_policy_), config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())), enabled_(false), remote_config_applied_(false), #if defined(OS_ANDROID) foreground_fetch_pending_(false), #endif previous_request_failed_authentication_(false), failed_attempts_before_success_(0), fetch_in_progress_(false), client_config_override_used_(false) { DCHECK(request_options); DCHECK(config_values); DCHECK(config); DCHECK(io_data); DCHECK(config_service_url_.is_valid()); DCHECK(!params::IsIncludedInHoldbackFieldTrial()); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); client_config_override_ = command_line.GetSwitchValueASCII( switches::kDataReductionProxyServerClientConfig); thread_checker_.DetachFromThread(); }
172,419
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 ResourceFetcher::StartLoad(Resource* resource) { DCHECK(resource); DCHECK(resource->StillNeedsLoad()); ResourceRequest request(resource->GetResourceRequest()); ResourceLoader* loader = nullptr; { Resource::RevalidationStartForbiddenScope revalidation_start_forbidden_scope(resource); ScriptForbiddenIfMainThreadScope script_forbidden_scope; if (!Context().ShouldLoadNewResource(resource->GetType()) && IsMainThread()) { GetMemoryCache()->Remove(resource); return false; } ResourceResponse response; blink::probe::PlatformSendRequest probe(&Context(), resource->Identifier(), request, response, resource->Options().initiator_info); Context().DispatchWillSendRequest(resource->Identifier(), request, response, resource->Options().initiator_info); SecurityOrigin* source_origin = Context().GetSecurityOrigin(); if (source_origin && source_origin->HasSuborigin()) request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone); resource->SetResourceRequest(request); loader = ResourceLoader::Create(this, scheduler_, resource); if (resource->ShouldBlockLoadEvent()) loaders_.insert(loader); else non_blocking_loaders_.insert(loader); StorePerformanceTimingInitiatorInformation(resource); resource->SetFetcherSecurityOrigin(source_origin); Resource::ProhibitAddRemoveClientInScope prohibit_add_remove_client_in_scope(resource); resource->NotifyStartLoad(); } loader->Start(); return true; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
bool ResourceFetcher::StartLoad(Resource* resource) { DCHECK(resource); DCHECK(resource->StillNeedsLoad()); ResourceRequest request(resource->GetResourceRequest()); ResourceLoader* loader = nullptr; { Resource::RevalidationStartForbiddenScope revalidation_start_forbidden_scope(resource); ScriptForbiddenIfMainThreadScope script_forbidden_scope; if (!Context().ShouldLoadNewResource(resource->GetType()) && IsMainThread()) { GetMemoryCache()->Remove(resource); return false; } ResourceResponse response; blink::probe::PlatformSendRequest probe(&Context(), resource->Identifier(), request, response, resource->Options().initiator_info); Context().DispatchWillSendRequest(resource->Identifier(), request, response, resource->GetType(), resource->Options().initiator_info); SecurityOrigin* source_origin = Context().GetSecurityOrigin(); if (source_origin && source_origin->HasSuborigin()) request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone); resource->SetResourceRequest(request); loader = ResourceLoader::Create(this, scheduler_, resource); if (resource->ShouldBlockLoadEvent()) loaders_.insert(loader); else non_blocking_loaders_.insert(loader); StorePerformanceTimingInitiatorInformation(resource); resource->SetFetcherSecurityOrigin(source_origin); Resource::ProhibitAddRemoveClientInScope prohibit_add_remove_client_in_scope(resource); resource->NotifyStartLoad(); } loader->Start(); return true; }
172,479
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 SimpleSoftOMXComponent::onPortEnable(OMX_U32 portIndex, bool enable) { CHECK_LT(portIndex, mPorts.size()); PortInfo *port = &mPorts.editItemAt(portIndex); CHECK_EQ((int)port->mTransition, (int)PortInfo::NONE); CHECK(port->mDef.bEnabled == !enable); if (!enable) { port->mDef.bEnabled = OMX_FALSE; port->mTransition = PortInfo::DISABLING; for (size_t i = 0; i < port->mBuffers.size(); ++i) { BufferInfo *buffer = &port->mBuffers.editItemAt(i); if (buffer->mOwnedByUs) { buffer->mOwnedByUs = false; if (port->mDef.eDir == OMX_DirInput) { notifyEmptyBufferDone(buffer->mHeader); } else { CHECK_EQ(port->mDef.eDir, OMX_DirOutput); notifyFillBufferDone(buffer->mHeader); } } } port->mQueue.clear(); } else { port->mTransition = PortInfo::ENABLING; } checkTransitions(); } Commit Message: omx: prevent input port enable/disable for software codecs Bug: 29421804 Change-Id: Iba1011e9af942a6dff7f659af769a51e3f5ba66f CWE ID: CWE-264
void SimpleSoftOMXComponent::onPortEnable(OMX_U32 portIndex, bool enable) { CHECK_LT(portIndex, mPorts.size()); PortInfo *port = &mPorts.editItemAt(portIndex); CHECK_EQ((int)port->mTransition, (int)PortInfo::NONE); CHECK(port->mDef.bEnabled == !enable); if (port->mDef.eDir != OMX_DirOutput) { ALOGE("Port enable/disable allowed only on output ports."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); android_errorWriteLog(0x534e4554, "29421804"); return; } if (!enable) { port->mDef.bEnabled = OMX_FALSE; port->mTransition = PortInfo::DISABLING; for (size_t i = 0; i < port->mBuffers.size(); ++i) { BufferInfo *buffer = &port->mBuffers.editItemAt(i); if (buffer->mOwnedByUs) { buffer->mOwnedByUs = false; if (port->mDef.eDir == OMX_DirInput) { notifyEmptyBufferDone(buffer->mHeader); } else { CHECK_EQ(port->mDef.eDir, OMX_DirOutput); notifyFillBufferDone(buffer->mHeader); } } } port->mQueue.clear(); } else { port->mTransition = PortInfo::ENABLING; } checkTransitions(); }
173,416