instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } 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
void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); }
172,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ShellWindowFrameView::Layout() { gfx::Size close_size = close_button_->GetPreferredSize(); int closeButtonOffsetY = (kCaptionHeight - close_size.height()) / 2; int closeButtonOffsetX = closeButtonOffsetY; close_button_->SetBounds( width() - closeButtonOffsetX - close_size.width(), closeButtonOffsetY, close_size.width(), close_size.height()); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 [email protected] Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::Layout() { if (is_frameless_) return; gfx::Size close_size = close_button_->GetPreferredSize(); int closeButtonOffsetY = (kCaptionHeight - close_size.height()) / 2; int closeButtonOffsetX = closeButtonOffsetY; close_button_->SetBounds( width() - closeButtonOffsetX - close_size.width(), closeButtonOffsetY, close_size.width(), close_size.height()); }
170,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[13]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } } Commit Message: Fix blur coefficient calculation buffer overflow Found by fuzzer test case id:000082,sig:11,src:002579,op:havoc,rep:8. Correctness should be checked, but this fixes the overflow for good. CWE ID: CWE-119
static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[14]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } }
168,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static 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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void file_sb_list_add(struct file *file, struct super_block *sb) { if (likely(!(file->f_mode & FMODE_WRITE))) return; if (!S_ISREG(file_inode(file)->i_mode)) return; lg_local_lock(&files_lglock); __file_sb_list_add(file, sb); lg_local_unlock(&files_lglock); } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
void file_sb_list_add(struct file *file, struct super_block *sb)
166,798
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove; } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119
bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove || type == EventTypeNames::pointerover || type == EventTypeNames::pointerout || type == EventTypeNames::pointermove; }
171,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void NetworkHandler::DeleteCookies( const std::string& name, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, std::unique_ptr<DeleteCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &DeleteCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), base::BindOnce(&DeleteCookiesCallback::sendSuccess, std::move(callback)))); } 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 NetworkHandler::DeleteCookies( const std::string& name, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, std::unique_ptr<DeleteCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &DeleteCookiesOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), base::BindOnce(&DeleteCookiesCallback::sendSuccess, std::move(callback)))); }
172,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class"); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags = mrb_obj_ptr(self)->flags; return clone; } Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036 Copying all flags from the original object may overwrite the clone's flags e.g. the embedded flag. CWE ID: CWE-476
mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class"); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN; return clone; }
169,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BaseShadow::log_except(const char *msg) { ShadowExceptionEvent event; bool exception_already_logged = false; if(!msg) msg = ""; sprintf(event.message, msg); if ( BaseShadow::myshadow_ptr ) { BaseShadow *shadow = BaseShadow::myshadow_ptr; event.recvd_bytes = shadow->bytesSent(); event.sent_bytes = shadow->bytesReceived(); exception_already_logged = shadow->exception_already_logged; if (shadow->began_execution) { event.began_execution = TRUE; } } else { event.recvd_bytes = 0.0; event.sent_bytes = 0.0; } if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL)) { ::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n"); } } Commit Message: CWE ID: CWE-134
BaseShadow::log_except(const char *msg) { ShadowExceptionEvent event; bool exception_already_logged = false; if(!msg) msg = ""; sprintf(event.message, "%s", msg); if ( BaseShadow::myshadow_ptr ) { BaseShadow *shadow = BaseShadow::myshadow_ptr; event.recvd_bytes = shadow->bytesSent(); event.sent_bytes = shadow->bytesReceived(); exception_already_logged = shadow->exception_already_logged; if (shadow->began_execution) { event.began_execution = TRUE; } } else { event.recvd_bytes = 0.0; event.sent_bytes = 0.0; } if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL)) { ::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n"); } }
165,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } } Commit Message: imcb_file_send_start: handle ft attempts from non-existing users CWE ID: CWE-476
file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start && bu) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } }
168,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_display_language) PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); if (!element || (!base::Contains(web_input_to_password_info_, *element) && !base::Contains(password_to_username_, *element))) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; } Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering Use for TouchToFill the same triggering logic that is used for regular suggestions. Bug: 1010233 Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230 Commit-Queue: Boris Sazonov <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Cr-Commit-Position: refs/heads/master@{#702058} CWE ID: CWE-125
bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); WebInputElement username_element; WebInputElement password_element; PasswordInfo* password_info = nullptr; if (!element || !FindPasswordInfoForElement(*element, &username_element, &password_element, &password_info)) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; }
172,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int open_debug_log(void) { /* don't do anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* don't do anything if we're not debugging */ if(debug_level == DEBUGL_NONE) return OK; if((debug_file_fp = fopen(debug_file, "a+")) == NULL) return ERROR; (void)fcntl(fileno(debug_file_fp), F_SETFD, FD_CLOEXEC); return OK; } Commit Message: Merge branch 'maint' CWE ID: CWE-264
int open_debug_log(void) { int open_debug_log(void) { int fh; struct stat st; /* don't do anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* don't do anything if we're not debugging */ if(debug_level == DEBUGL_NONE) return OK; if ((fh = open(debug_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) return ERROR; if((debug_file_fp = fdopen(fh, "a+")) == NULL) return ERROR; if ((fstat(fh, &st)) == -1) { debug_file_fp = NULL; close(fh); return ERROR; } if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) { debug_file_fp = NULL; close(fh); return ERROR; } (void)fcntl(fh, F_SETFD, FD_CLOEXEC); return OK; }
166,859
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) free (gf->file->device->disk); free (gf->file); free (gf); } } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) { free (gf->file->device->disk); } free (gf->file); free (gf); } }
168,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_item_->RemoveObserver(this); std::string name = base::UTF16ToUTF8(folder_name_view_->text()); delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); } Commit Message: Enforce the maximum length of the folder name in UI. BUG=355797 [email protected] Review URL: https://codereview.chromium.org/203863005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_name_view_->Update(); folder_item_->RemoveObserver(this); // Enforce the maximum folder name length in UI. std::string name = base::UTF16ToUTF8( folder_name_view_->text().substr(0, kMaxFolderNameChars)); if (name != folder_item_->name()) delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); }
171,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)
166,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int SocketStream::DoBeforeConnect() { next_state_ = STATE_BEFORE_CONNECT_COMPLETE; if (!context_.get() || !context_->network_delegate()) { return OK; } int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect( this, io_callback_); if (result != OK && result != ERR_IO_PENDING) next_state_ = STATE_CLOSE; return result; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int SocketStream::DoBeforeConnect() { next_state_ = STATE_BEFORE_CONNECT_COMPLETE; if (!context_ || !context_->network_delegate()) return OK; int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect( this, io_callback_); if (result != OK && result != ERR_IO_PENDING) next_state_ = STATE_CLOSE; return result; }
171,253
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size) { struct inode *inode = d_inode(dentry); struct buffer_head *bh = NULL; int error; struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); ea_idebug(inode, "buffer=%p, buffer_size=%ld", buffer, (long)buffer_size); error = 0; if (!EXT4_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %llu", (unsigned long long)EXT4_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount)); if (ext4_xattr_check_block(inode, bh)) { EXT4_ERROR_INODE(inode, "bad block %llu", EXT4_I(inode)->i_file_acl); error = -EFSCORRUPTED; goto cleanup; } ext4_xattr_cache_insert(ext4_mb_cache, bh); error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size); cleanup: brelse(bh); return error; } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size) { struct inode *inode = d_inode(dentry); struct buffer_head *bh = NULL; int error; struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); ea_idebug(inode, "buffer=%p, buffer_size=%ld", buffer, (long)buffer_size); error = 0; if (!EXT4_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %llu", (unsigned long long)EXT4_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount)); if (ext4_xattr_check_block(inode, bh)) { EXT4_ERROR_INODE(inode, "bad block %llu", EXT4_I(inode)->i_file_acl); error = -EFSCORRUPTED; goto cleanup; } ext4_xattr_cache_insert(ext4_mb_cache, bh); error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size); cleanup: brelse(bh); return error; }
169,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UpdateContentLengthPrefs(int received_content_length, int original_content_length, bool via_data_reduction_proxy) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); if (!g_browser_process) return; PrefService* prefs = g_browser_process->local_state(); if (!prefs) return; #if defined(OS_ANDROID) bool with_data_reduction_proxy_enabled = g_browser_process->profile_manager()->GetDefaultProfile()-> GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif chrome_browser_net::UpdateContentLengthPrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, via_data_reduction_proxy, prefs); } 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, void UpdateContentLengthPrefs( int received_content_length, int original_content_length, chrome_browser_net::DataReductionRequestType data_reduction_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); if (!g_browser_process) return; PrefService* prefs = g_browser_process->local_state(); if (!prefs) return; #if defined(OS_ANDROID) bool with_data_reduction_proxy_enabled = g_browser_process->profile_manager()->GetDefaultProfile()-> GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif chrome_browser_net::UpdateContentLengthPrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, data_reduction_type, prefs); }
171,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: base::string16 IDNToUnicodeWithAdjustments( base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) { if (adjustments) adjustments->clear(); base::string16 input16; input16.reserve(host.length()); input16.insert(input16.end(), host.begin(), host.end()); base::string16 out16; for (size_t component_start = 0, component_end; component_start < input16.length(); component_start = component_end + 1) { component_end = input16.find('.', component_start); if (component_end == base::string16::npos) component_end = input16.length(); // For getting the last component. size_t component_length = component_end - component_start; size_t new_component_start = out16.length(); bool converted_idn = false; if (component_end > component_start) { converted_idn = IDNToUnicodeOneComponent(input16.data() + component_start, component_length, &out16); } size_t new_component_length = out16.length() - new_component_start; if (converted_idn && adjustments) { adjustments->push_back(base::OffsetAdjuster::Adjustment( component_start, component_length, new_component_length)); } if (component_end < input16.length()) out16.push_back('.'); } return out16; } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
base::string16 IDNToUnicodeWithAdjustments( base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) { if (adjustments) adjustments->clear(); base::string16 input16; input16.reserve(host.length()); input16.insert(input16.end(), host.begin(), host.end()); bool is_tld_ascii = true; size_t last_dot = host.rfind('.'); if (last_dot != base::StringPiece::npos && host.substr(last_dot).starts_with(".xn--")) { is_tld_ascii = false; } base::string16 out16; for (size_t component_start = 0, component_end; component_start < input16.length(); component_start = component_end + 1) { component_end = input16.find('.', component_start); if (component_end == base::string16::npos) component_end = input16.length(); // For getting the last component. size_t component_length = component_end - component_start; size_t new_component_start = out16.length(); bool converted_idn = false; if (component_end > component_start) { converted_idn = IDNToUnicodeOneComponent(input16.data() + component_start, component_length, is_tld_ascii, &out16); } size_t new_component_length = out16.length() - new_component_start; if (converted_idn && adjustments) { adjustments->push_back(base::OffsetAdjuster::Adjustment( component_start, component_length, new_component_length)); } if (component_end < input16.length()) out16.push_back('.'); } return out16; }
172,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool HTMLMediaElement::isAutoplayAllowedPerSettings() const { LocalFrame* frame = document().frame(); if (!frame) return false; FrameLoaderClient* frameLoaderClient = frame->loader().client(); return frameLoaderClient && frameLoaderClient->allowAutoplay(false); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119
bool HTMLMediaElement::isAutoplayAllowedPerSettings() const { LocalFrame* frame = document().frame(); if (!frame) return false; FrameLoaderClient* frameLoaderClient = frame->loader().client(); return frameLoaderClient && frameLoaderClient->allowAutoplay(true); }
172,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind()
167,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len) { if (!m_debug.outfile) { int size = 0; if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.outfile_name, size); } m_debug.outfile = fopen(m_debug.outfile_name, "ab"); if (!m_debug.outfile) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d", m_debug.outfile_name, errno); m_debug.outfile_name[0] = '\0'; return -1; } } if (m_debug.outfile && buffer_len) { DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len); fwrite(buffer_addr, buffer_len, 1, m_debug.outfile); } return 0; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len) { if (venc_handle->is_secure_session()) { DEBUG_PRINT_ERROR("logging secure output buffers is not allowed!"); return -1; } if (!m_debug.outfile) { int size = 0; if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.outfile_name, size); } m_debug.outfile = fopen(m_debug.outfile_name, "ab"); if (!m_debug.outfile) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d", m_debug.outfile_name, errno); m_debug.outfile_name[0] = '\0'; return -1; } } if (m_debug.outfile && buffer_len) { DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len); fwrite(buffer_addr, buffer_len, 1, m_debug.outfile); } return 0; }
173,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Initialize(ChannelLayout channel_layout, int bits_per_channel) { AudioParameters params( media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout, kSamplesPerSecond, bits_per_channel, kRawDataSize); algorithm_.Initialize(1, params, base::Bind( &AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this))); EnqueueData(); } 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
void Initialize(ChannelLayout channel_layout, int bits_per_channel) { void Initialize(ChannelLayout channel_layout, int bits_per_channel, int samples_per_second) { static const int kFrames = kRawDataSize / ((kDefaultSampleBits / 8) * ChannelLayoutToChannelCount(kDefaultChannelLayout)); AudioParameters params( media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout, samples_per_second, bits_per_channel, kFrames); algorithm_.Initialize(1, params, base::Bind( &AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this))); EnqueueData(); }
171,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) { ASSERT(!getThreadState()->sweepForbidden()); ASSERT(header->checkHeader()); Address address = reinterpret_cast<Address>(header); Address payload = header->payload(); size_t size = header->size(); size_t payloadSize = header->payloadSize(); ASSERT(size > 0); ASSERT(pageFromObject(address) == findPageFromAddress(address)); { ThreadState::SweepForbiddenScope forbiddenScope(getThreadState()); header->finalize(payload, payloadSize); if (address + size == m_currentAllocationPoint) { m_currentAllocationPoint = address; setRemainingAllocationSize(m_remainingAllocationSize + size); SET_MEMORY_INACCESSIBLE(address, size); return; } SET_MEMORY_INACCESSIBLE(payload, payloadSize); header->markPromptlyFreed(); } m_promptlyFreedSize += size; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) { ASSERT(!getThreadState()->sweepForbidden()); header->checkHeader(); Address address = reinterpret_cast<Address>(header); Address payload = header->payload(); size_t size = header->size(); size_t payloadSize = header->payloadSize(); ASSERT(size > 0); ASSERT(pageFromObject(address) == findPageFromAddress(address)); { ThreadState::SweepForbiddenScope forbiddenScope(getThreadState()); header->finalize(payload, payloadSize); if (address + size == m_currentAllocationPoint) { m_currentAllocationPoint = address; setRemainingAllocationSize(m_remainingAllocationSize + size); SET_MEMORY_INACCESSIBLE(address, size); return; } SET_MEMORY_INACCESSIBLE(payload, payloadSize); header->markPromptlyFreed(); } m_promptlyFreedSize += size; }
172,714
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS err = parseVps(data + 2, size - 2); break; case 33: // SPS err = parseSps(data + 2, size - 2); break; case 34: // PPS err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; } Commit Message: Validate lengths in HEVC metadata parsing Add code to validate the size parameter passed to HecvParameterSets::addNalUnit(). Previously vulnerable to decrementing an unsigned past 0, yielding a huge result value. Bug: 35467107 Test: ran POC, no crash, emitted new "bad length" log entry Change-Id: Ia169b9edc1e0f7c5302e3c68aa90a54e8863d79e (cherry picked from commit e0dcf097cc029d056926029a29419e1650cbdf1b) CWE ID: CWE-476
status_t HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { if (size < 1) { ALOGE("empty NAL b/35467107"); return ERROR_MALFORMED; } uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS if (size < 2) { ALOGE("invalid NAL/VPS size b/35467107"); return ERROR_MALFORMED; } err = parseVps(data + 2, size - 2); break; case 33: // SPS if (size < 2) { ALOGE("invalid NAL/SPS size b/35467107"); return ERROR_MALFORMED; } err = parseSps(data + 2, size - 2); break; case 34: // PPS if (size < 2) { ALOGE("invalid NAL/PPS size b/35467107"); return ERROR_MALFORMED; } err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; }
174,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int vmxnet3_post_load(void *opaque, int version_id) { VMXNET3State *s = opaque; PCIDevice *d = PCI_DEVICE(s); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); if (s->msix_used) { if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) { VMW_WRPRN("Failed to re-use MSI-X vectors"); msix_uninit(d, &s->msix_bar, &s->msix_bar); s->msix_used = false; return -1; } } return 0; } Commit Message: CWE ID: CWE-20
static int vmxnet3_post_load(void *opaque, int version_id) { VMXNET3State *s = opaque; PCIDevice *d = PCI_DEVICE(s); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); if (s->msix_used) { if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) { VMW_WRPRN("Failed to re-use MSI-X vectors"); msix_uninit(d, &s->msix_bar, &s->msix_bar); s->msix_used = false; return -1; } } vmxnet3_validate_interrupts(s); return 0; }
165,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: 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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(RenderProcessHost::FromID(worker_process_id_), nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } 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 ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); }
172,783
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET])
167,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; assert((cc%(2*stride))==0); if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++) wc -= stride; } while (wc > 0); } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; if((cc%(2*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "horAcc16", "%s", "cc%(2*stride))!=0"); return 0; } if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++) wc -= stride; } while (wc > 0); } return 1; }
166,882
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) { int i, j, sym, wordsize; ut32 stype; wordsize = MACH0_(get_bits)(bin) / 8; if (idx < 0 || idx >= bin->nsymtab) { return 0; } if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) { stype = S_LAZY_SYMBOL_POINTERS; } else { stype = S_NON_LAZY_SYMBOL_POINTERS; } reloc->offset = 0; reloc->addr = 0; reloc->addend = 0; #define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return false; } #undef CASE for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == stype) { for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++) if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) { sym = j; break; } reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; return true; } } return false; } Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026) CWE ID: CWE-125
static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) { int i, j, sym, wordsize; ut32 stype; wordsize = MACH0_(get_bits)(bin) / 8; if (idx < 0 || idx >= bin->nsymtab) { return 0; } if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) { stype = S_LAZY_SYMBOL_POINTERS; } else { stype = S_NON_LAZY_SYMBOL_POINTERS; } reloc->offset = 0; reloc->addr = 0; reloc->addend = 0; #define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return false; } #undef CASE for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == stype) { for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) { int indidx = bin->sects[i].reserved1 + j; if (indidx < 0 || indidx >= bin->nindirectsyms) { break; } if (idx == bin->indirectsyms[indidx]) { sym = j; break; } } reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; return true; } } return false; }
169,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool FrameSelection::IsHandleVisible() const { return GetSelectionInDOMTree().IsHandleVisible(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool FrameSelection::IsHandleVisible() const {
171,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; } Commit Message: CWE ID:
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
164,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); SkRegion* region = new SkRegion; size_t size = p->readInt32(); region->readFromMemory(p->readInplace(size), size); return reinterpret_cast<jlong>(region); } Commit Message: Check that the parcel contained the expected amount of region data. DO NOT MERGE bug:20883006 Change-Id: Ib47a8ec8696dbc37e958b8dbceb43fcbabf6605b CWE ID: CWE-264
static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const size_t size = p->readInt32(); const void* regionData = p->readInplace(size); if (regionData == NULL) { return NULL; } SkRegion* region = new SkRegion; region->readFromMemory(regionData, size); return reinterpret_cast<jlong>(region); }
173,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->headindex < psf->headend) { ptr [k] = psf->header [psf->headindex] ; psf->headindex ++ ; } else { psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ; ptr [k] = psf->header [psf->headindex] ; psf->headindex = psf->headend ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; if (psf->header.indx + bufsize >= psf->header.len && psf_bump_header_allocation (psf, bufsize)) return 0 ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->header.indx < psf->header.end) { ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx ++ ; } else { psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, 1, psf) ; ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx = psf->header.end ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */
170,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void vnc_async_encoding_start(VncState *orig, VncState *local) { local->vnc_encoding = orig->vnc_encoding; local->features = orig->features; local->ds = orig->ds; local->vd = orig->vd; local->lossy_rect = orig->lossy_rect; local->write_pixels = orig->write_pixels; local->clientds = orig->clientds; local->tight = orig->tight; local->zlib = orig->zlib; local->hextile = orig->hextile; local->output = queue->buffer; local->csock = -1; /* Don't do any network work on this thread */ buffer_reset(&local->output); } Commit Message: CWE ID: CWE-125
static void vnc_async_encoding_start(VncState *orig, VncState *local) { local->vnc_encoding = orig->vnc_encoding; local->features = orig->features; local->ds = orig->ds; local->vd = orig->vd; local->lossy_rect = orig->lossy_rect; local->write_pixels = orig->write_pixels; local->client_pf = orig->client_pf; local->client_be = orig->client_be; local->tight = orig->tight; local->zlib = orig->zlib; local->hextile = orig->hextile; local->output = queue->buffer; local->csock = -1; /* Don't do any network work on this thread */ buffer_reset(&local->output); }
165,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); rcu_read_lock(); final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; }
167,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void uwbd_start(struct uwb_rc *rc) { rc->uwbd.task = kthread_run(uwbd, rc, "uwbd"); if (rc->uwbd.task == NULL) printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); else rc->uwbd.pid = rc->uwbd.task->pid; } Commit Message: uwb: properly check kthread_run return value uwbd_start() calls kthread_run() and checks that the return value is not NULL. But the return value is not NULL in case kthread_run() fails, it takes the form of ERR_PTR(-EINTR). Use IS_ERR() instead. Also add a check to uwbd_stop(). Signed-off-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
void uwbd_start(struct uwb_rc *rc) { struct task_struct *task = kthread_run(uwbd, rc, "uwbd"); if (IS_ERR(task)) { rc->uwbd.task = NULL; printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); } else { rc->uwbd.task = task; rc->uwbd.pid = rc->uwbd.task->pid; } }
167,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mIsBackup) { return; } memcpy(header->pBuffer + header->nOffset, (const OMX_U8 *)mMem->pointer() + header->nOffset, header->nFilledLen); } 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
void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mCopyToOmx) { return; } memcpy(header->pBuffer + header->nOffset, (const OMX_U8 *)mMem->pointer() + header->nOffset, header->nFilledLen); }
174,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); return map->FindProcess(site); } Commit Message: Check for appropriate bindings in process-per-site mode. BUG=174059 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12188025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); // See if we have an existing process with appropriate bindings for this site. // If not, the caller should create a new process and register it. std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); RenderProcessHost* host = map->FindProcess(site); if (host && !IsSuitableHost(host, browser_context, url)) { // The registered process does not have an appropriate set of bindings for // the url. Remove it from the map so we can register a better one. RecordAction(UserMetricsAction("BindingsMismatch_GetProcessHostPerSite")); map->RemoveProcess(host); host = NULL; } return host; }
171,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } Commit Message: bluetooth: Validate socket address length in sco_sock_bind(). Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (addr_len < sizeof(struct sockaddr_sco)) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; }
167,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){ long i; for(i=0; i<=w-sizeof(long); i+=sizeof(long)){ long a = *(long*)(src+i); long b = *(long*)(dst+i); *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80); } for(; i<w; i++) dst[i+0] += src[i+0]; } Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-189
static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){ long i; for(i=0; i<=w-(int)sizeof(long); i+=sizeof(long)){ long a = *(long*)(src+i); long b = *(long*)(dst+i); *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80); } for(; i<w; i++) dst[i+0] += src[i+0]; }
165,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void EnterpriseEnrollmentScreen::RegisterForDevicePolicy( const std::string& token, policy::BrowserPolicyConnector::TokenType token_type) { policy::BrowserPolicyConnector* connector = g_browser_process->browser_policy_connector(); if (!connector->device_cloud_policy_subsystem()) { NOTREACHED() << "Cloud policy subsystem not initialized."; UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOtherFailed, policy::kMetricEnrollmentSize); if (is_showing_) actor_->ShowFatalEnrollmentError(); return; } connector->ScheduleServiceInitialization(0); registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar( connector->device_cloud_policy_subsystem(), this)); connector->SetDeviceCredentials(user_, token, token_type); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void EnterpriseEnrollmentScreen::RegisterForDevicePolicy( const std::string& token, policy::BrowserPolicyConnector::TokenType token_type) { policy::BrowserPolicyConnector* connector = g_browser_process->browser_policy_connector(); if (!connector->device_cloud_policy_subsystem()) { NOTREACHED() << "Cloud policy subsystem not initialized."; UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOtherFailed, policy::kMetricEnrollmentSize); if (is_showing_) actor_->ShowFatalEnrollmentError(); return; } connector->ScheduleServiceInitialization(0); registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar( connector->device_cloud_policy_subsystem(), this)); connector->RegisterForDevicePolicy(user_, token, token_type); }
170,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, bigint *modulus, bigint *pub_exp) { int i, size; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; i = 10; /* start at the first possible non-padded byte */ while (block[i++] && i < sig_len); size = sig_len - i; /* get only the bit we want */ if (size > 0) { int len; const uint8_t *sig_ptr = get_signature(&block[i], &len); if (sig_ptr) { bir = bi_import(ctx, sig_ptr, len); } } free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; } Commit Message: Apply CVE fixes for X509 parsing Apply patches developed by Sze Yiu which correct a vulnerability in X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info. CWE ID: CWE-347
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, uint8_t sig_type, bigint *modulus, bigint *pub_exp) { int i; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); const uint8_t *sig_prefix = NULL; uint8_t sig_prefix_size = 0, hash_len = 0; /* adjust our expections */ switch (sig_type) { case SIG_TYPE_MD5: sig_prefix = sig_prefix_md5; sig_prefix_size = sizeof(sig_prefix_md5); break; case SIG_TYPE_SHA1: sig_prefix = sig_prefix_sha1; sig_prefix_size = sizeof(sig_prefix_sha1); break; case SIG_TYPE_SHA256: sig_prefix = sig_prefix_sha256; sig_prefix_size = sizeof(sig_prefix_sha256); break; case SIG_TYPE_SHA384: sig_prefix = sig_prefix_sha384; sig_prefix_size = sizeof(sig_prefix_sha384); break; case SIG_TYPE_SHA512: sig_prefix = sig_prefix_sha512; sig_prefix_size = sizeof(sig_prefix_sha512); break; } if (sig_prefix) hash_len = sig_prefix[sig_prefix_size - 1]; /* check length (#A) */ if (sig_len < 2 + 8 + 1 + sig_prefix_size + hash_len) goto err; /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* check the first 2 bytes */ if (block[0] != 0 || block[1] != 1) goto err; /* check the padding */ i = 2; /* start at the first padding byte */ while (i < sig_len - 1 - sig_prefix_size - hash_len) { /* together with (#A), we require at least 8 bytes of padding */ if (block[i++] != 0xFF) goto err; } /* check end of padding */ if (block[i++] != 0) goto err; /* check the ASN.1 metadata */ if (memcmp_P(block+i, sig_prefix, sig_prefix_size)) goto err; /* now we can get the hash we need */ bir = bi_import(ctx, block + i + sig_prefix_size, hash_len); err: free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; }
169,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure(buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; } Commit Message: CWE ID:
hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure (buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; }
164,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */
167,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeMockRenderThread::OnUpdatePrintSettings( int document_cookie, const base::DictionaryValue& job_settings, PrintMsg_PrintPages_Params* params) { std::string dummy_string; int margins_type = 0; if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) || !job_settings.GetBoolean(printing::kSettingCollate, NULL) || !job_settings.GetInteger(printing::kSettingColor, NULL) || !job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) || !job_settings.GetBoolean(printing::kIsFirstRequest, NULL) || !job_settings.GetString(printing::kSettingDeviceName, &dummy_string) || !job_settings.GetInteger(printing::kSettingDuplexMode, NULL) || !job_settings.GetInteger(printing::kSettingCopies, NULL) || !job_settings.GetString(printing::kPreviewUIAddr, &dummy_string) || !job_settings.GetInteger(printing::kPreviewRequestID, NULL) || !job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) { return; } if (printer_.get()) { const ListValue* page_range_array; printing::PageRanges new_ranges; if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) { for (size_t index = 0; index < page_range_array->GetSize(); ++index) { const base::DictionaryValue* dict; if (!page_range_array->GetDictionary(index, &dict)) continue; printing::PageRange range; if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) || !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) { continue; } range.from--; range.to--; new_ranges.push_back(range); } } std::vector<int> pages(printing::PageRange::GetPages(new_ranges)); printer_->UpdateSettings(document_cookie, params, pages, margins_type); } } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnUpdatePrintSettings( int document_cookie, const base::DictionaryValue& job_settings, PrintMsg_PrintPages_Params* params) { std::string dummy_string; int margins_type = 0; if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) || !job_settings.GetBoolean(printing::kSettingCollate, NULL) || !job_settings.GetInteger(printing::kSettingColor, NULL) || !job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) || !job_settings.GetBoolean(printing::kIsFirstRequest, NULL) || !job_settings.GetString(printing::kSettingDeviceName, &dummy_string) || !job_settings.GetInteger(printing::kSettingDuplexMode, NULL) || !job_settings.GetInteger(printing::kSettingCopies, NULL) || !job_settings.GetInteger(printing::kPreviewUIID, NULL) || !job_settings.GetInteger(printing::kPreviewRequestID, NULL) || !job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) { return; } const ListValue* page_range_array; printing::PageRanges new_ranges; if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) { for (size_t index = 0; index < page_range_array->GetSize(); ++index) { const base::DictionaryValue* dict; if (!page_range_array->GetDictionary(index, &dict)) continue; printing::PageRange range; if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) || !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) { continue; } // Page numbers are 1-based in the dictionary. // Page numbers are 0-based for the printing context. range.from--; range.to--; new_ranges.push_back(range); } } std::vector<int> pages(printing::PageRange::GetPages(new_ranges)); printer_->UpdateSettings(document_cookie, params, pages, margins_type); } MockPrinter* ChromeMockRenderThread::printer() { return printer_.get(); }
170,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftG711::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; if (pcmParams->nPortIndex == 0) { pcmParams->ePCMMode = mIsMLaw ? OMX_AUDIO_PCMModeMULaw : OMX_AUDIO_PCMModeALaw; } else { pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; } pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftG711::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; if (pcmParams->nPortIndex == 0) { pcmParams->ePCMMode = mIsMLaw ? OMX_AUDIO_PCMModeMULaw : OMX_AUDIO_PCMModeALaw; } else { pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; } pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,205
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; } Commit Message: CWE ID: CWE-119
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { *session_data_size = psession.size; ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
164,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const char *cJSON_GetErrorPtr( void ) { return ep; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
const char *cJSON_GetErrorPtr( void )
167,288
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; desc = get_desc(sel); if (!desc) return -1L; return get_desc_base(desc); } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; if (!get_desc(&desc, sel)) return -1L; return get_desc_base(&desc); }
169,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HTMLFormControlElement::updateVisibleValidationMessage() { Page* page = document().page(); if (!page) return; String message; if (layoutObject() && willValidate()) message = validationMessage().stripWhiteSpace(); m_hasValidationMessage = true; ValidationMessageClient* client = &page->validationMessageClient(); TextDirection messageDir = LTR; TextDirection subMessageDir = LTR; String subMessage = validationSubMessage().stripWhiteSpace(); if (message.isEmpty()) client->hideValidationMessage(*this); else findCustomValidationMessageTextDirection(message, messageDir, subMessage, subMessageDir); client->showValidationMessage(*this, message, messageDir, subMessage, subMessageDir); } Commit Message: Form validation: Do not show validation bubble if the page is invisible. BUG=673163 Review-Url: https://codereview.chromium.org/2572813003 Cr-Commit-Position: refs/heads/master@{#438476} CWE ID: CWE-1021
void HTMLFormControlElement::updateVisibleValidationMessage() { Page* page = document().page(); if (!page || !page->isPageVisible()) return; String message; if (layoutObject() && willValidate()) message = validationMessage().stripWhiteSpace(); m_hasValidationMessage = true; ValidationMessageClient* client = &page->validationMessageClient(); TextDirection messageDir = LTR; TextDirection subMessageDir = LTR; String subMessage = validationSubMessage().stripWhiteSpace(); if (message.isEmpty()) client->hideValidationMessage(*this); else findCustomValidationMessageTextDirection(message, messageDir, subMessage, subMessageDir); client->showValidationMessage(*this, message, messageDir, subMessage, subMessageDir); }
172,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; upperdentry = ovl_dentry_upper(dentry); if (upperdentry) { mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } else { err = ovl_copy_up_last(dentry, attr, false); } ovl_drop_write(dentry); out: return err; } Commit Message: ovl: fix permission checking for setattr [Al Viro] The bug is in being too enthusiastic about optimizing ->setattr() away - instead of "copy verbatim with metadata" + "chmod/chown/utimes" (with the former being always safe and the latter failing in case of insufficient permissions) it tries to combine these two. Note that copyup itself will have to do ->setattr() anyway; _that_ is where the elevated capabilities are right. Having these two ->setattr() (one to set verbatim copy of metadata, another to do what overlayfs ->setattr() had been asked to do in the first place) combined is where it breaks. Signed-off-by: Miklos Szeredi <[email protected]> Cc: <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; err = ovl_copy_up(dentry); if (!err) { upperdentry = ovl_dentry_upper(dentry); mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } ovl_drop_write(dentry); out: return err; }
166,559
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Cues::PreloadCuePoint( long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size; CuePoint** const qq = new CuePoint*[n]; CuePoint** q = qq; //beginning of target CuePoint** p = m_cue_points; //beginning of source CuePoint** const pp = p + m_preload_count; //end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Cues::PreloadCuePoint( continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; // consume payload assert(m_pos <= stop); return true; // yes, we loaded a cue point } // return (m_pos < stop); return false; // no, we did not load a cue point }
174,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() { return syslogs_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() {
170,631
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: off_t HFSForkReadStream::Seek(off_t offset, int whence) { DCHECK_EQ(SEEK_SET, whence); DCHECK_GE(offset, 0); DCHECK_LT(static_cast<uint64_t>(offset), fork_.logicalSize); size_t target_block = offset / hfs_->block_size(); size_t block_count = 0; for (size_t i = 0; i < arraysize(fork_.extents); ++i) { const HFSPlusExtentDescriptor* extent = &fork_.extents[i]; if (extent->startBlock == 0 && extent->blockCount == 0) break; base::CheckedNumeric<size_t> new_block_count(block_count); new_block_count += extent->blockCount; if (!new_block_count.IsValid()) { DLOG(ERROR) << "Seek offset block count overflows"; return false; } if (target_block < new_block_count.ValueOrDie()) { if (current_extent_ != i) { read_current_extent_ = false; current_extent_ = i; } auto iterator_block_offset = base::CheckedNumeric<size_t>(block_count) * hfs_->block_size(); if (!iterator_block_offset.IsValid()) { DLOG(ERROR) << "Seek block offset overflows"; return false; } fork_logical_offset_ = offset; return offset; } block_count = new_block_count.ValueOrDie(); } return -1; } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
off_t HFSForkReadStream::Seek(off_t offset, int whence) { DCHECK_EQ(SEEK_SET, whence); DCHECK_GE(offset, 0); DCHECK(offset == 0 || static_cast<uint64_t>(offset) < fork_.logicalSize); size_t target_block = offset / hfs_->block_size(); size_t block_count = 0; for (size_t i = 0; i < arraysize(fork_.extents); ++i) { const HFSPlusExtentDescriptor* extent = &fork_.extents[i]; if (extent->startBlock == 0 && extent->blockCount == 0) break; base::CheckedNumeric<size_t> new_block_count(block_count); new_block_count += extent->blockCount; if (!new_block_count.IsValid()) { DLOG(ERROR) << "Seek offset block count overflows"; return false; } if (target_block < new_block_count.ValueOrDie()) { if (current_extent_ != i) { read_current_extent_ = false; current_extent_ = i; } auto iterator_block_offset = base::CheckedNumeric<size_t>(block_count) * hfs_->block_size(); if (!iterator_block_offset.IsValid()) { DLOG(ERROR) << "Seek block offset overflows"; return false; } fork_logical_offset_ = offset; return offset; } block_count = new_block_count.ValueOrDie(); } return -1; }
171,717
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long VideoTrack::GetWidth() const { return m_width; } 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::GetWidth() const
174,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; } Commit Message: Change ECDSA signing to use blinding. CWE ID: CWE-200
static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; }
169,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&) { ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this); if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage()) return; FloatRect boundingBox = repaintRectInLocalCoordinates(); if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo)) return; PaintInfo childPaintInfo(paintInfo); bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline); if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) { GraphicsContextStateSaver stateSaver(*childPaintInfo.context); childPaintInfo.applyTransform(m_localTransform); if (childPaintInfo.phase == PaintPhaseForeground) { SVGRenderingContext renderingContext(this, childPaintInfo); if (renderingContext.isRenderingPrepared()) { if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground)) return; paintForeground(childPaintInfo); } } if (drawsOutline) paintOutline(childPaintInfo, IntRect(boundingBox)); } } Commit Message: Avoid drawing SVG image content when the image is of zero size. R=pdr BUG=330420 Review URL: https://codereview.chromium.org/109753004 git-svn-id: svn://svn.chromium.org/blink/trunk@164536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&) { ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this); if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage()) return; FloatRect boundingBox = repaintRectInLocalCoordinates(); if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo)) return; PaintInfo childPaintInfo(paintInfo); bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline); if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) { GraphicsContextStateSaver stateSaver(*childPaintInfo.context); childPaintInfo.applyTransform(m_localTransform); if (childPaintInfo.phase == PaintPhaseForeground && !m_objectBoundingBox.isEmpty()) { SVGRenderingContext renderingContext(this, childPaintInfo); if (renderingContext.isRenderingPrepared()) { if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground)) return; paintForeground(childPaintInfo); } } if (drawsOutline) paintOutline(childPaintInfo, IntRect(boundingBox)); } }
171,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) fz_throw(ctx, FZ_ERROR_GENERIC, "negative xref stream entry index"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; } Commit Message: CWE ID: CWE-119
pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i0 > PDF_MAX_OBJECT_NUMBER || i1 < 0 || i1 > PDF_MAX_OBJECT_NUMBER || i0 + i1 - 1 > PDF_MAX_OBJECT_NUMBER) fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; }
165,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AccessibilityExpanded AXNodeObject::isExpanded() const { if (getNode() && isHTMLSummaryElement(*getNode())) { if (getNode()->parentNode() && isHTMLDetailsElement(getNode()->parentNode())) return toElement(getNode()->parentNode())->hasAttribute(openAttr) ? ExpandedExpanded : ExpandedCollapsed; } const AtomicString& expanded = getAttribute(aria_expandedAttr); if (equalIgnoringCase(expanded, "true")) return ExpandedExpanded; if (equalIgnoringCase(expanded, "false")) return ExpandedCollapsed; return ExpandedUndefined; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityExpanded AXNodeObject::isExpanded() const { if (getNode() && isHTMLSummaryElement(*getNode())) { if (getNode()->parentNode() && isHTMLDetailsElement(getNode()->parentNode())) return toElement(getNode()->parentNode())->hasAttribute(openAttr) ? ExpandedExpanded : ExpandedCollapsed; } const AtomicString& expanded = getAttribute(aria_expandedAttr); if (equalIgnoringASCIICase(expanded, "true")) return ExpandedExpanded; if (equalIgnoringASCIICase(expanded, "false")) return ExpandedCollapsed; return ExpandedUndefined; }
171,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); } Commit Message: CWE ID: CWE-17
static void build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { /* This is also used by ICMPv6 and nf_conntrack_ipv6 is optional */ if (!nfct_attr_is_set(ct, ATTR_ICMP_TYPE)) return; ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); }
164,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_expand_gray_1_2_4_to_8_set( PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_gray_1_2_4_to_8_set( const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); /* NOTE: don't expect this to expand tRNS */ this->next->set(this->next, that, pp, pi); }
173,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) { pthread_mutex_lock(&slot_lock); rfc_slot_t *slot = find_rfc_slot_by_id(user_id); if (!slot) goto out; bool need_close = false; if (flags & SOCK_THREAD_FD_RD && !slot->f.server) { if (slot->f.connected) { int size = 0; if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) pthread_mutex_unlock(&slot_lock); BTA_JvRfcommWrite(slot->rfc_handle, slot->id); } else { LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn); need_close = true; } } if (flags & SOCK_THREAD_FD_WR) { if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) { LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn); need_close = true; } } if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) { int size = 0; if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) { pthread_mutex_lock(&slot_lock); rfc_slot_t *slot = find_rfc_slot_by_id(user_id); if (!slot) goto out; bool need_close = false; if (flags & SOCK_THREAD_FD_RD && !slot->f.server) { if (slot->f.connected) { int size = 0; if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) == 0 && size)) { BTA_JvRfcommWrite(slot->rfc_handle, slot->id); } } else { LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn); need_close = true; } } if (flags & SOCK_THREAD_FD_WR) { if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) { LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn); need_close = true; } } if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) { int size = 0; if (need_close || TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) != 0 || !size) cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); }
173,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserView::TabDetachedAt(TabContents* contents, int index) { if (index == browser_->active_index()) { contents_container_->SetWebContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserView::TabDetachedAt(TabContents* contents, int index) { void BrowserView::TabDetachedAt(WebContents* contents, int index) { if (index == browser_->active_index()) { contents_container_->SetWebContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } }
171,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TabManagerTest() : scoped_set_tick_clock_for_testing_(&test_clock_) { test_clock_.Advance(kShortDelay); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
TabManagerTest() : scoped_set_tick_clock_for_testing_(&test_clock_) { test_clock_.Advance(kShortDelay); scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); }
172,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac) { struct cm_id_private *cm_id_priv; cm_id_priv = container_of(id, struct cm_id_private, id); if (smac != NULL) memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac)); if (alt_smac != NULL) memcpy(cm_id_priv->alt_av.smac, alt_smac, sizeof(cm_id_priv->alt_av.smac)); return 0; } Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <[email protected]> Signed-off-by: Or Gerlitz <[email protected]> Signed-off-by: Roland Dreier <[email protected]> CWE ID: CWE-20
int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
166,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void TabContentsContainerGtk::DetachTab(TabContents* tab) { gfx::NativeView widget = tab->web_contents()->GetNativeView(); if (widget) { GtkWidget* parent = gtk_widget_get_parent(widget); if (parent) { DCHECK_EQ(parent, expanded_); gtk_container_remove(GTK_CONTAINER(expanded_), widget); } } } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void TabContentsContainerGtk::DetachTab(TabContents* tab) { void TabContentsContainerGtk::DetachTab(WebContents* tab) { gfx::NativeView widget = tab->GetNativeView(); if (widget) { GtkWidget* parent = gtk_widget_get_parent(widget); if (parent) { DCHECK_EQ(parent, expanded_); gtk_container_remove(GTK_CONTAINER(expanded_), widget); } } }
171,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; } Commit Message: kexec/uefi: copy secure_boot flag in boot params across kexec reboot Kexec reboot in case secure boot being enabled does not keep the secure boot mode in new kernel, so later one can load unsigned kernel via legacy kexec_load. In this state, the system is missing the protections provided by secure boot. Adding a patch to fix this by retain the secure_boot flag in original kernel. secure_boot flag in boot_params is set in EFI stub, but kexec bypasses the stub. Fixing this issue by copying secure_boot flag across kexec reboot. Signed-off-by: Dave Young <[email protected]> CWE ID: CWE-254
setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; params->secure_boot = boot_params.secure_boot; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; }
168,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BluetoothDeviceChromeOS::SetPinCode(const std::string& pincode) { if (!agent_.get() || pincode_callback_.is_null()) return; pincode_callback_.Run(SUCCESS, pincode); pincode_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::SetPinCode(const std::string& pincode) { if (!pairing_context_.get()) return; pairing_context_->SetPinCode(pincode); }
171,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error) { *ret = g_ascii_strup (str, -1); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error)
165,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int needs_empty_write(sector_t block, struct inode *inode) { int error; struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; bh_map.b_size = 1 << inode->i_blkbits; error = gfs2_block_map(inode, block, &bh_map, 0); if (unlikely(error)) return error; return !buffer_mapped(&bh_map); } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119
static int needs_empty_write(sector_t block, struct inode *inode)
166,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } Commit Message: Fix write heap buffer overflow in opj_mqc_byteout(). Discovered by Ke Liu of Tencent's Xuanwu LAB (#835) CWE ID: CWE-119
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }
168,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b, *avail, nl); if (len >= 0) len += tested; } return (len); } Commit Message: Issue 747 (and others?): Avoid OOB read when parsing multiple long lines The mtree bidder needs to look several lines ahead in the input. It does this by extending the read-ahead and parsing subsequent lines from the same growing buffer. A bookkeeping error when extending the read-ahead would sometimes lead it to significantly over-count the size of the line being read. CWE ID: CWE-125
next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b + len, *avail - len, nl); if (len >= 0) len += tested; } return (len); }
168,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void *hashtable_iter_at(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash % num_buckets(hashtable)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return &pair->list; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
void *hashtable_iter_at(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash & hashmask(hashtable->order)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return &pair->list; }
166,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); first_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); first_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); }
172,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return; } FinishCacheSelection(NULL, NULL); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { bool AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { if (was_select_cache_called_) return false; DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return true; } FinishCacheSelection(NULL, NULL); return true; }
171,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ParamTraits<AudioParameters>::Read(const Message* m, PickleIterator* iter, AudioParameters* r) { int format, channel_layout, sample_rate, bits_per_sample, frames_per_buffer, channels; if (!m->ReadInt(iter, &format) || !m->ReadInt(iter, &channel_layout) || !m->ReadInt(iter, &sample_rate) || !m->ReadInt(iter, &bits_per_sample) || !m->ReadInt(iter, &frames_per_buffer) || !m->ReadInt(iter, &channels)) return false; r->Reset(static_cast<AudioParameters::Format>(format), static_cast<ChannelLayout>(channel_layout), sample_rate, bits_per_sample, frames_per_buffer); return true; } 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
bool ParamTraits<AudioParameters>::Read(const Message* m, PickleIterator* iter, AudioParameters* r) { int format, channel_layout, sample_rate, bits_per_sample, frames_per_buffer, channels; if (!m->ReadInt(iter, &format) || !m->ReadInt(iter, &channel_layout) || !m->ReadInt(iter, &sample_rate) || !m->ReadInt(iter, &bits_per_sample) || !m->ReadInt(iter, &frames_per_buffer) || !m->ReadInt(iter, &channels)) return false; r->Reset(static_cast<AudioParameters::Format>(format), static_cast<ChannelLayout>(channel_layout), sample_rate, bits_per_sample, frames_per_buffer); if (!r->IsValid()) return false; return true; }
171,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: extract_header_length(uint16_t fc) { int len = 0; switch ((fc >> 10) & 0x3) { case 0x00: if (fc & (1 << 6)) /* intra-PAN with none dest addr */ return -1; break; case 0x01: return -1; case 0x02: len += 4; break; case 0x03: len += 10; break; } switch ((fc >> 14) & 0x3) { case 0x00: break; case 0x01: return -1; case 0x02: len += 4; break; case 0x03: len += 10; break; } if (fc & (1 << 6)) { if (len < 2) return -1; len -= 2; } return len; } Commit Message: CVE-2017-13000/IEEE 802.15.4: Add more bounds checks. While we're at it, add a bunch of macros for the frame control field's subfields, have the reserved frame types show the frame type value, use the same code path for processing source and destination addresses regardless of whether -v was specified (just leave out the addresses in non-verbose mode), and return the header length in all cases. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
extract_header_length(uint16_t fc)
170,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RunInvAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; } fwd_txfm_ref(in, coeff, pitch_, tx_type_); REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; EXPECT_GE(1u, error) << "Error: 16x16 IDCT has error " << error << " at index " << j; } } } 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 RunInvAccuracyCheck() { void RunInvAccuracyCheck(int limit) { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; in[j] = src16[j] - dst16[j]; #endif } } fwd_txfm_ref(in, coeff, pitch_, tx_type_); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const uint32_t diff = dst[j] - src[j]; #endif const uint32_t error = diff * diff; EXPECT_GE(static_cast<uint32_t>(limit), error) << "Error: 4x4 IDCT has error " << error << " at index " << j; } } }
174,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) { NOTREACHED(); return false; } policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { // Renderers need to copy sections for plugin DIBs and GPU. sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; // Renderers need to share events with plugins. result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec) { if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; return 0; } Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw() the only non-trivial detail is that we do it before rw_verify_area(), so we'd better cap the length ourselves in aio_setup_single_rw() case (for vectored case rw_copy_check_uvector() will do that for us). Signed-off-by: Al Viro <[email protected]> CWE ID:
static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec, struct iov_iter *iter) { if (len > MAX_RW_COUNT) len = MAX_RW_COUNT; if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; iov_iter_init(iter, rw, iovec, *nr_segs, len); return 0; }
170,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: struct inode *isofs_iget(struct super_block *sb, unsigned long block, unsigned long offset) { unsigned long hashval; struct inode *inode; struct isofs_iget5_callback_data data; long ret; if (offset >= 1ul << sb->s_blocksize_bits) return ERR_PTR(-EINVAL); data.block = block; data.offset = offset; hashval = (block << sb->s_blocksize_bits) | offset; inode = iget5_locked(sb, hashval, &isofs_iget5_test, &isofs_iget5_set, &data); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { ret = isofs_read_inode(inode); if (ret < 0) { iget_failed(inode); inode = ERR_PTR(ret); } else { unlock_new_inode(inode); } } return inode; } Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
struct inode *isofs_iget(struct super_block *sb, struct inode *__isofs_iget(struct super_block *sb, unsigned long block, unsigned long offset, int relocated) { unsigned long hashval; struct inode *inode; struct isofs_iget5_callback_data data; long ret; if (offset >= 1ul << sb->s_blocksize_bits) return ERR_PTR(-EINVAL); data.block = block; data.offset = offset; hashval = (block << sb->s_blocksize_bits) | offset; inode = iget5_locked(sb, hashval, &isofs_iget5_test, &isofs_iget5_set, &data); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { ret = isofs_read_inode(inode, relocated); if (ret < 0) { iget_failed(inode); inode = ERR_PTR(ret); } else { unlock_new_inode(inode); } } return inode; }
166,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void *atomic_thread(void *context) { struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context; for (int i = 0; i < at->max_val; i++) { usleep(1); atomic_inc_prefix_s32(&at->data[i]); } return NULL; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void *atomic_thread(void *context) { struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context; for (int i = 0; i < at->max_val; i++) { TEMP_FAILURE_RETRY(usleep(1)); atomic_inc_prefix_s32(&at->data[i]); } return NULL; }
173,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream) { UWORD16 u2_mb_addr_incr = 0; while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE) { impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN); u2_mb_addr_incr += 33; } u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) + MB_ADDR_INCR_OFFSET; return(u2_mb_addr_incr); } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream) { UWORD16 u2_mb_addr_incr = 0; while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN); u2_mb_addr_incr += 33; } u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) + MB_ADDR_INCR_OFFSET; return(u2_mb_addr_incr); }
173,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void uwbd_stop(struct uwb_rc *rc) { kthread_stop(rc->uwbd.task); uwbd_flush(rc); } Commit Message: uwb: properly check kthread_run return value uwbd_start() calls kthread_run() and checks that the return value is not NULL. But the return value is not NULL in case kthread_run() fails, it takes the form of ERR_PTR(-EINTR). Use IS_ERR() instead. Also add a check to uwbd_stop(). Signed-off-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
void uwbd_stop(struct uwb_rc *rc) { if (rc->uwbd.task) kthread_stop(rc->uwbd.task); uwbd_flush(rc); }
167,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } if (length > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }
167,067
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ProcPseudoramiXGetScreenSize(ClientPtr client) { REQUEST(xPanoramiXGetScreenSizeReq); WindowPtr pWin; xPanoramiXGetScreenSizeReply rep; register int rc; TRACE; if (stuff->screen >= pseudoramiXNumScreens) return BadMatch; REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; rep.type = X_Reply; rep.length = 0; rep.sequenceNumber = client->sequence; /* screen dimensions */ rep.width = pseudoramiXScreens[stuff->screen].w; rep.height = pseudoramiXScreens[stuff->screen].h; rep.window = stuff->window; rep.screen = stuff->screen; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.width); swapl(&rep.height); swapl(&rep.window); swapl(&rep.screen); } WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply),&rep); return Success; } Commit Message: CWE ID: CWE-20
ProcPseudoramiXGetScreenSize(ClientPtr client) { REQUEST(xPanoramiXGetScreenSizeReq); WindowPtr pWin; xPanoramiXGetScreenSizeReply rep; register int rc; TRACE; REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq); if (stuff->screen >= pseudoramiXNumScreens) return BadMatch; rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; rep.type = X_Reply; rep.length = 0; rep.sequenceNumber = client->sequence; /* screen dimensions */ rep.width = pseudoramiXScreens[stuff->screen].w; rep.height = pseudoramiXScreens[stuff->screen].h; rep.window = stuff->window; rep.screen = stuff->screen; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.width); swapl(&rep.height); swapl(&rep.window); swapl(&rep.screen); } WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply),&rep); return Success; }
165,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { struct ring_buffer *buf; if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); buf = tr->trace_buffer.buffer; tr->trace_buffer.buffer = tr->max_buffer.buffer; tr->max_buffer.buffer = buf; __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787
update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); swap(tr->trace_buffer.buffer, tr->max_buffer.buffer); __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); }
169,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context, MIMETypeCheck mime_type_check) const { if (ErrorOccurred()) return false; KURL sheet_url = GetResponse().Url(); if (sheet_url.IsLocalFile()) { if (parser_context) { parser_context->Count(WebFeature::kLocalCSSFile); } String extension; int last_dot = sheet_url.LastPathComponent().ReverseFind('.'); if (last_dot != -1) extension = sheet_url.LastPathComponent().Substring(last_dot + 1); if (!EqualIgnoringASCIICase( MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) { if (parser_context) { parser_context->CountDeprecation( WebFeature::kLocalCSSFileExtensionRejected); } if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) { return false; } } } if (mime_type_check == MIMETypeCheck::kLax) return true; AtomicString content_type = HttpContentType(); return content_type.IsEmpty() || DeprecatedEqualIgnoringCase(content_type, "text/css") || DeprecatedEqualIgnoringCase(content_type, "application/x-unknown-content-type"); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254
bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context, MIMETypeCheck mime_type_check) const { if (ErrorOccurred()) return false; KURL sheet_url = GetResponse().Url(); if (sheet_url.IsLocalFile()) { if (parser_context) { parser_context->Count(WebFeature::kLocalCSSFile); } String extension; int last_dot = sheet_url.LastPathComponent().ReverseFind('.'); if (last_dot != -1) extension = sheet_url.LastPathComponent().Substring(last_dot + 1); if (!EqualIgnoringASCIICase( MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) { if (parser_context) { parser_context->CountDeprecation( WebFeature::kLocalCSSFileExtensionRejected); } return false; } } if (mime_type_check == MIMETypeCheck::kLax) return true; AtomicString content_type = HttpContentType(); return content_type.IsEmpty() || DeprecatedEqualIgnoringCase(content_type, "text/css") || DeprecatedEqualIgnoringCase(content_type, "application/x-unknown-content-type"); }
173,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size, int32 id_request, IPC::Message* reply_message) { TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer"); if (command_buffer_.get()) { int32 id = command_buffer_->CreateTransferBuffer(size, id_request); GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams( reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); } Commit Message: Sizes going across an IPC should be uint32. BUG=164946 Review URL: https://chromiumcodereview.appspot.com/11472038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size, void GpuCommandBufferStub::OnCreateTransferBuffer(uint32 size, int32 id_request, IPC::Message* reply_message) { TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer"); if (command_buffer_.get()) { int32 id = command_buffer_->CreateTransferBuffer(size, id_request); GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams( reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); }
171,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t* buf, int buf_size) { int size, i; uint8_t *ppcm[4] = {0}; if (buf_size < DV_PROFILE_BYTES || !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) || buf_size < c->sys->frame_size) { return -1; /* Broken frame, or not enough data */ } /* Queueing audio packet */ /* FIXME: in case of no audio/bad audio we have to do something */ size = dv_extract_audio_info(c, buf); for (i = 0; i < c->ach; i++) { c->audio_pkt[i].size = size; c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate; ppcm[i] = c->audio_buf[i]; } dv_extract_audio(buf, ppcm, c->sys); /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ if (buf[1] & 0x0C) { c->audio_pkt[2].size = c->audio_pkt[3].size = 0; } else { c->audio_pkt[0].size = c->audio_pkt[1].size = 0; c->abytes += size; } } else { c->abytes += size; } Commit Message: CWE ID: CWE-119
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t* buf, int buf_size) { int size, i; uint8_t *ppcm[4] = {0}; if (buf_size < DV_PROFILE_BYTES || !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) || buf_size < c->sys->frame_size) { return -1; /* Broken frame, or not enough data */ } /* Queueing audio packet */ /* FIXME: in case of no audio/bad audio we have to do something */ size = dv_extract_audio_info(c, buf); for (i = 0; i < c->ach; i++) { c->audio_pkt[i].size = size; c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate; ppcm[i] = c->audio_buf[i]; } if (c->ach) dv_extract_audio(buf, ppcm, c->sys); /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ if (buf[1] & 0x0C) { c->audio_pkt[2].size = c->audio_pkt[3].size = 0; } else { c->audio_pkt[0].size = c->audio_pkt[1].size = 0; c->abytes += size; } } else { c->abytes += size; }
165,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UrlFetcherDownloader::StartURLFetch(const GURL& url) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (download_dir_.empty()) { Result result; result.error = -1; DownloadMetrics download_metrics; download_metrics.url = url; download_metrics.downloader = DownloadMetrics::kUrlFetcher; download_metrics.error = -1; download_metrics.downloaded_bytes = -1; download_metrics.total_bytes = -1; download_metrics.download_time_ms = 0; main_task_runner()->PostTask( FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete, base::Unretained(this), false, result, download_metrics)); return; } const auto file_path = download_dir_.AppendASCII(url.ExtractFileName()); network_fetcher_ = network_fetcher_factory_->Create(); network_fetcher_->DownloadToFile( url, file_path, base::BindOnce(&UrlFetcherDownloader::OnResponseStarted, base::Unretained(this)), base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress, base::Unretained(this)), base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete, base::Unretained(this), file_path)); download_start_time_ = base::TimeTicks::Now(); } Commit Message: Fix error handling in the request sender and url fetcher downloader. That means handling the network errors by primarily looking at net_error. Bug: 1028369 Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428 Reviewed-by: Joshua Pawlicki <[email protected]> Commit-Queue: Sorin Jianu <[email protected]> Cr-Commit-Position: refs/heads/master@{#719199} CWE ID: CWE-20
void UrlFetcherDownloader::StartURLFetch(const GURL& url) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (download_dir_.empty()) { Result result; result.error = -1; DownloadMetrics download_metrics; download_metrics.url = url; download_metrics.downloader = DownloadMetrics::kUrlFetcher; download_metrics.error = -1; download_metrics.downloaded_bytes = -1; download_metrics.total_bytes = -1; download_metrics.download_time_ms = 0; main_task_runner()->PostTask( FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete, base::Unretained(this), false, result, download_metrics)); return; } file_path_ = download_dir_.AppendASCII(url.ExtractFileName()); network_fetcher_ = network_fetcher_factory_->Create(); network_fetcher_->DownloadToFile( url, file_path_, base::BindOnce(&UrlFetcherDownloader::OnResponseStarted, base::Unretained(this)), base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress, base::Unretained(this)), base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete, base::Unretained(this))); download_start_time_ = base::TimeTicks::Now(); }
172,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const { if (frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight)); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 [email protected] Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const { if (is_frameless_ || frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight)); }
170,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CallbackAndDie(bool succeeded) { v8::Isolate* isolate = context_->isolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Value> args[] = {v8::Boolean::New(isolate, succeeded)}; context_->CallFunction(v8::Local<v8::Function>::New(isolate, callback_), arraysize(args), args); delete this; } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID:
void CallbackAndDie(bool succeeded) { // Use PostTask to avoid running user scripts while handling this // DidFailProvisionalLoad notification. base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(callback_, false)); delete this; }
172,144
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = l2t_send(tdev, skb, l2e); if (error < 0) kfree_skb(skb); return error; } Commit Message: iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <[email protected]> Signed-off-by: Hariprasad Shenai <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID:
static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = l2t_send(tdev, skb, l2e); if (error < 0) kfree_skb(skb); return error < 0 ? error : 0; }
167,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fdct16x16_c(in, out, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void fdct16x16_ref(const int16_t *in, tran_low_t *out, int stride, int /*tx_type*/) { vpx_fdct16x16_c(in, out, stride); }
174,529
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void NaClProcessHost::OnProcessLaunched() { FilePath irt_path; const char* irt_path_var = getenv("NACL_IRT_LIBRARY"); if (irt_path_var != NULL) { FilePath::StringType string(irt_path_var, irt_path_var + strlen(irt_path_var)); irt_path = FilePath(string); } else { FilePath plugin_dir; if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) { LOG(ERROR) << "Failed to locate the plugins directory"; delete this; return; } irt_path = plugin_dir.Append(GetIrtLibraryFilename()); } base::FileUtilProxy::CreateOrOpenCallback* callback = callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone); if (!base::FileUtilProxy::CreateOrOpen( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), irt_path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ, callback)) { delete callback; delete this; } } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void NaClProcessHost::OnProcessLaunched() { FilePath irt_path; const char* irt_path_var = getenv("NACL_IRT_LIBRARY"); if (irt_path_var != NULL) { FilePath::StringType string(irt_path_var, irt_path_var + strlen(irt_path_var)); irt_path = FilePath(string); } else { FilePath plugin_dir; if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) { LOG(ERROR) << "Failed to locate the plugins directory"; delete this; return; } irt_path = plugin_dir.Append(GetIrtLibraryFilename()); } base::FileUtilProxy::CreateOrOpenCallback* callback = callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone); if (!base::FileUtilProxy::CreateOrOpen( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), irt_path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ, callback)) { delete this; } }
170,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ResourceFetcher::DidLoadResourceFromMemoryCache( unsigned long identifier, Resource* resource, const ResourceRequest& original_resource_request) { ResourceRequest resource_request(resource->Url()); resource_request.SetFrameType(original_resource_request.GetFrameType()); resource_request.SetRequestContext( original_resource_request.GetRequestContext()); Context().DispatchDidLoadResourceFromMemoryCache(identifier, resource_request, resource->GetResponse()); Context().DispatchWillSendRequest(identifier, resource_request, ResourceResponse() /* redirects */, resource->Options().initiator_info); Context().DispatchDidReceiveResponse( identifier, resource->GetResponse(), resource_request.GetFrameType(), resource_request.GetRequestContext(), resource, FetchContext::ResourceResponseType::kFromMemoryCache); if (resource->EncodedSize() > 0) Context().DispatchDidReceiveData(identifier, 0, resource->EncodedSize()); Context().DispatchDidFinishLoading( identifier, 0, 0, resource->GetResponse().DecodedBodyLength()); } 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
void ResourceFetcher::DidLoadResourceFromMemoryCache( unsigned long identifier, Resource* resource, const ResourceRequest& original_resource_request) { ResourceRequest resource_request(resource->Url()); resource_request.SetFrameType(original_resource_request.GetFrameType()); resource_request.SetRequestContext( original_resource_request.GetRequestContext()); Context().DispatchDidLoadResourceFromMemoryCache(identifier, resource_request, resource->GetResponse()); Context().DispatchWillSendRequest( identifier, resource_request, ResourceResponse() /* redirects */, resource->GetType(), resource->Options().initiator_info); Context().DispatchDidReceiveResponse( identifier, resource->GetResponse(), resource_request.GetFrameType(), resource_request.GetRequestContext(), resource, FetchContext::ResourceResponseType::kFromMemoryCache); if (resource->EncodedSize() > 0) Context().DispatchDidReceiveData(identifier, 0, resource->EncodedSize()); Context().DispatchDidFinishLoading( identifier, 0, 0, resource->GetResponse().DecodedBodyLength()); }
172,478