instruction
stringclasses
1 value
input
stringlengths
64
129k
output
int64
0
1
__index_level_0__
int64
0
30k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderViewHostImpl::OnSelectionChanged(const string16& text, size_t offset, const ui::Range& range) { if (view_) view_->SelectionChanged(text, offset, range); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
10,044
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22
1
29,771
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void stringAttrWithSetterExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { ExceptionState exceptionState(ExceptionState::SetterContext, "stringAttrWithSetterException", "TestObject", info.Holder(), info.GetIsolate()); TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setStringAttrWithSetterException(cppValue, exceptionState); exceptionState.throwIfNeeded(); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
9,260
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int inttgt_to_output(int inttgt) { int i; for (i = 0; i < ARRAY_SIZE(inttgt_output); i++) { if (inttgt_output[i][0] == inttgt) { return inttgt_output[i][1]; } } fprintf(stderr, "%s: unsupported inttgt %d\n", __func__, inttgt); return OPENPIC_OUTPUT_INT; } Commit Message: CWE ID: CWE-119
0
5,086
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: OperationID FileSystemOperationRunner::Remove(const FileSystemURL& url, bool recursive, StatusCallback callback) { base::File::Error error = base::File::FILE_OK; std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); OperationID id = BeginOperation(std::move(operation)); base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { DidFinish(id, std::move(callback), error); return id; } PrepareForWrite(id, url); operation_raw->Remove(url, recursive, base::BindOnce(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, std::move(callback))); return id; } Commit Message: [FileSystem] Harden against overflows of OperationID a bit better. Rather than having a UAF when OperationID overflows instead overwrite the old operation with the new one. Can still cause weirdness, but at least won't result in UAF. Also update OperationID to uint64_t to make sure we don't overflow to begin with. Bug: 925864 Change-Id: Ifdf3fa0935ab5ea8802d91bba39601f02b0dbdc9 Reviewed-on: https://chromium-review.googlesource.com/c/1441498 Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#627115} CWE ID: CWE-190
0
18,969
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Status IndexedDBDatabase::PutOperation( std::unique_ptr<PutOperationParams> params, IndexedDBTransaction* transaction) { IDB_TRACE2("IndexedDBDatabase::PutOperation", "txn.id", transaction->id(), "size", params->value.SizeEstimate()); DCHECK_NE(transaction->mode(), blink::kWebIDBTransactionModeReadOnly); bool key_was_generated = false; Status s = Status::OK(); DCHECK(metadata_.object_stores.find(params->object_store_id) != metadata_.object_stores.end()); const IndexedDBObjectStoreMetadata& object_store = metadata_.object_stores[params->object_store_id]; DCHECK(object_store.auto_increment || params->key->IsValid()); std::unique_ptr<IndexedDBKey> key; if (params->put_mode != blink::kWebIDBPutModeCursorUpdate && object_store.auto_increment && !params->key->IsValid()) { std::unique_ptr<IndexedDBKey> auto_inc_key = GenerateKey( backing_store_.get(), transaction, id(), params->object_store_id); key_was_generated = true; if (!auto_inc_key->IsValid()) { params->callbacks->OnError( IndexedDBDatabaseError(blink::kWebIDBDatabaseExceptionConstraintError, "Maximum key generator value reached.")); return s; } key = std::move(auto_inc_key); } else { key = std::move(params->key); } DCHECK(key->IsValid()); IndexedDBBackingStore::RecordIdentifier record_identifier; if (params->put_mode == blink::kWebIDBPutModeAddOnly) { bool found = false; Status found_status = backing_store_->KeyExistsInObjectStore( transaction->BackingStoreTransaction(), id(), params->object_store_id, *key, &record_identifier, &found); if (!found_status.ok()) return found_status; if (found) { params->callbacks->OnError( IndexedDBDatabaseError(blink::kWebIDBDatabaseExceptionConstraintError, "Key already exists in the object store.")); return found_status; } } std::vector<std::unique_ptr<IndexWriter>> index_writers; base::string16 error_message; bool obeys_constraints = false; bool backing_store_success = MakeIndexWriters(transaction, backing_store_.get(), id(), object_store, *key, key_was_generated, params->index_keys, &index_writers, &error_message, &obeys_constraints); if (!backing_store_success) { params->callbacks->OnError(IndexedDBDatabaseError( blink::kWebIDBDatabaseExceptionUnknownError, "Internal error: backing store error updating index keys.")); return s; } if (!obeys_constraints) { params->callbacks->OnError(IndexedDBDatabaseError( blink::kWebIDBDatabaseExceptionConstraintError, error_message)); return s; } s = backing_store_->PutRecord(transaction->BackingStoreTransaction(), id(), params->object_store_id, *key, &params->value, &params->handles, &record_identifier); if (!s.ok()) return s; { IDB_TRACE1("IndexedDBDatabase::PutOperation.UpdateIndexes", "txn.id", transaction->id()); for (const auto& writer : index_writers) { writer->WriteIndexKeys(record_identifier, backing_store_.get(), transaction->BackingStoreTransaction(), id(), params->object_store_id); } } if (object_store.auto_increment && params->put_mode != blink::kWebIDBPutModeCursorUpdate && key->type() == kWebIDBKeyTypeNumber) { IDB_TRACE1("IndexedDBDatabase::PutOperation.AutoIncrement", "txn.id", transaction->id()); s = UpdateKeyGenerator(backing_store_.get(), transaction, id(), params->object_store_id, *key, !key_was_generated); if (!s.ok()) return s; } { IDB_TRACE1("IndexedDBDatabase::PutOperation.Callbacks", "txn.id", transaction->id()); params->callbacks->OnSuccess(*key); } FilterObservation(transaction, params->object_store_id, params->put_mode == blink::kWebIDBPutModeAddOnly ? blink::kWebIDBAdd : blink::kWebIDBPut, IndexedDBKeyRange(*key), &params->value); factory_->NotifyIndexedDBContentChanged( origin(), metadata_.name, metadata_.object_stores[params->object_store_id].name); return s; } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Commit-Queue: Victor Costan <pwnall@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
0
15,639
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void red_channel_client_send_set_ack(RedChannelClient *rcc) { SpiceMsgSetAck ack; spice_assert(rcc); red_channel_client_init_send_data(rcc, SPICE_MSG_SET_ACK, NULL); ack.generation = ++rcc->ack_data.generation; ack.window = rcc->ack_data.client_window; rcc->ack_data.messages_window = 0; spice_marshall_msg_set_ack(rcc->send_data.marshaller, &ack); red_channel_client_begin_send_message(rcc); } Commit Message: CWE ID: CWE-399
0
2,655
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void *rose_neigh_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return (v == SEQ_START_TOKEN) ? rose_neigh_list : ((struct rose_neigh *)v)->next; } Commit Message: rose: Add length checks to CALL_REQUEST parsing Define some constant offsets for CALL_REQUEST based on the description at <http://www.techfest.com/networking/wan/x25plp.htm> and the definition of ROSE as using 10-digit (5-byte) addresses. Use them consistently. Validate all implicit and explicit facilities lengths. Validate the address length byte rather than either trusting or assuming its value. Signed-off-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
22,466
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int nicklist_compare(NICK_REC *p1, NICK_REC *p2, const char *nick_prefix) { int i; if (p1 == NULL) return -1; if (p2 == NULL) return 1; if (p1->prefixes[0] == p2->prefixes[0]) return g_ascii_strcasecmp(p1->nick, p2->nick); if (!p1->prefixes[0]) return 1; if (!p2->prefixes[0]) return -1; /* They aren't equal. We've taken care of that already. * The first one we encounter in this list is the greater. */ for (i = 0; nick_prefix[i] != '\0'; i++) { if (p1->prefixes[0] == nick_prefix[i]) return -1; if (p2->prefixes[0] == nick_prefix[i]) return 1; } /* we should never have gotten here... */ return g_ascii_strcasecmp(p1->nick, p2->nick); } Commit Message: Merge branch 'security' into 'master' Security Closes #10 See merge request !17 CWE ID: CWE-416
0
961
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void HTMLFormControlElement::disabledAttributeChanged() { setNeedsWillValidateCheck(); pseudoStateChanged(CSSSelector::PseudoDisabled); pseudoStateChanged(CSSSelector::PseudoEnabled); if (layoutObject()) LayoutTheme::theme().controlStateChanged(*layoutObject(), EnabledControlState); if (isDisabledFormControl() && adjustedFocusedElementInTreeScope() == this) { document().setNeedsFocusedElementCheck(); } } 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
0
16,151
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ChromeContentRendererClient::PrefetchHostName(const char* hostname, size_t length) { net_predictor_->Resolve(hostname, length); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
7,436
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number) { #ifndef WITH_SSH1 fatal("no SSH protocol 1 support"); #else /* WITH_SSH1 */ struct session_state *state = ssh->state; const struct sshcipher *cipher = cipher_by_number(number); int r; const char *wmsg; if (cipher == NULL) fatal("%s: unknown cipher number %d", __func__, number); if (keylen < 20) fatal("%s: keylen too small: %d", __func__, keylen); if (keylen > SSH_SESSION_KEY_LENGTH) fatal("%s: keylen too big: %d", __func__, keylen); memcpy(state->ssh1_key, key, keylen); state->ssh1_keylen = keylen; if ((r = cipher_init(&state->send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT)) != 0 || (r = cipher_init(&state->receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT) != 0)) fatal("%s: cipher_init failed: %s", __func__, ssh_err(r)); if (!state->cipher_warning_done && ((wmsg = cipher_warning_message(&state->send_context)) != NULL || (wmsg = cipher_warning_message(&state->send_context)) != NULL)) { error("Warning: %s", wmsg); state->cipher_warning_done = 1; } #endif /* WITH_SSH1 */ } Commit Message: CWE ID: CWE-119
0
14,535
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int bar_read(struct pci_dev *dev, int offset, u32 * value, void *data) { struct pci_bar_info *bar = data; if (unlikely(!bar)) { pr_warn(DRV_NAME ": driver data not found for %s\n", pci_name(dev)); return XEN_PCI_ERR_op_failed; } *value = bar->which ? bar->len_val : bar->val; return 0; } Commit Message: xen-pciback: limit guest control of command register Otherwise the guest can abuse that control to cause e.g. PCIe Unsupported Request responses by disabling memory and/or I/O decoding and subsequently causing (CPU side) accesses to the respective address ranges, which (depending on system configuration) may be fatal to the host. Note that to alter any of the bits collected together as PCI_COMMAND_GUEST permissive mode is now required to be enabled globally or on the specific device. This is CVE-2015-2150 / XSA-120. Signed-off-by: Jan Beulich <jbeulich@suse.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Cc: <stable@vger.kernel.org> Signed-off-by: David Vrabel <david.vrabel@citrix.com> CWE ID: CWE-264
0
10,462
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void clear_nlink(struct inode *inode) { if (inode->i_nlink) { inode->__i_nlink = 0; atomic_long_inc(&inode->i_sb->s_remove_count); } } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <tytso@mit.edu> Cc: Serge Hallyn <serge.hallyn@ubuntu.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Dave Chinner <david@fromorbit.com> Cc: stable@vger.kernel.org Signed-off-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
0
3,470
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (SSL *ssl, SSL_SESSION *sess) { return ctx->new_session_cb; } Commit Message: CWE ID: CWE-190
0
15,548
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: const std::vector<ui::EventType>& events() const { return events_; }; Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
28,046
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Nullable<ExceptionCode> HTMLMediaElement::play() { BLINK_MEDIA_LOG << "play(" << (void*)this << ")"; if (!UserGestureIndicator::processingUserGesture()) { m_autoplayUmaHelper->onAutoplayInitiated(AutoplaySource::Method); if (isGestureNeededForPlayback()) { if (!m_paused) { playInternal(); return nullptr; } m_autoplayUmaHelper->recordCrossOriginAutoplayResult( CrossOriginAutoplayResult::AutoplayBlocked); String message = ExceptionMessages::failedToExecute( "play", "HTMLMediaElement", "API can only be initiated by a user gesture."); document().addConsoleMessage(ConsoleMessage::create( JSMessageSource, WarningMessageLevel, message)); return NotAllowedError; } else { if (isGestureNeededForPlaybackIfCrossOriginExperimentEnabled()) { m_autoplayUmaHelper->recordCrossOriginAutoplayResult( CrossOriginAutoplayResult::AutoplayBlocked); } else { m_autoplayUmaHelper->recordCrossOriginAutoplayResult( CrossOriginAutoplayResult::AutoplayAllowed); } } } else { m_autoplayUmaHelper->recordCrossOriginAutoplayResult( CrossOriginAutoplayResult::PlayedWithGesture); UserGestureIndicator::utilizeUserGesture(); unlockUserGesture(); } if (m_error && m_error->code() == MediaError::kMediaErrSrcNotSupported) return NotSupportedError; playInternal(); return nullptr; } 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
0
27,472
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline MagickBooleanType IsSkipTag(const char *tag) { register ssize_t i; i=0; while (skip_tags[i] != (const char *) NULL) { if (LocaleCompare(tag,skip_tags[i]) == 0) return(MagickTrue); i++; } return(MagickFalse); } Commit Message: Coder path traversal is not authorized, bug report provided by Masaaki Chida CWE ID: CWE-22
0
6,742
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void AutofillPopupViewViews::DoUpdateBoundsAndRedrawPopup() { gfx::Rect bounds = delegate()->popup_bounds(); SetSize(bounds.size()); gfx::Rect clipping_bounds = CalculateClippingBounds(); int available_vertical_space = clipping_bounds.height() - (bounds.y() - clipping_bounds.y()) - kPopupBottomMargin; if (available_vertical_space < bounds.height()) { const int extra_width = scroll_view_ ? scroll_view_->GetScrollBarLayoutWidth() : 0; bounds.set_width(bounds.width() + extra_width); bounds.set_height(available_vertical_space); } bounds.Inset(-GetWidget()->GetRootView()->border()->GetInsets()); GetWidget()->SetBounds(bounds); SchedulePaint(); } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
0
22,100
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs, struct bio_set *bs) { gfp_t saved_gfp = gfp_mask; unsigned front_pad; unsigned inline_vecs; struct bio_vec *bvl = NULL; struct bio *bio; void *p; if (!bs) { if (nr_iovecs > UIO_MAXIOV) return NULL; p = kmalloc(sizeof(struct bio) + nr_iovecs * sizeof(struct bio_vec), gfp_mask); front_pad = 0; inline_vecs = nr_iovecs; } else { /* should not use nobvec bioset for nr_iovecs > 0 */ if (WARN_ON_ONCE(!bs->bvec_pool && nr_iovecs > 0)) return NULL; /* * generic_make_request() converts recursion to iteration; this * means if we're running beneath it, any bios we allocate and * submit will not be submitted (and thus freed) until after we * return. * * This exposes us to a potential deadlock if we allocate * multiple bios from the same bio_set() while running * underneath generic_make_request(). If we were to allocate * multiple bios (say a stacking block driver that was splitting * bios), we would deadlock if we exhausted the mempool's * reserve. * * We solve this, and guarantee forward progress, with a rescuer * workqueue per bio_set. If we go to allocate and there are * bios on current->bio_list, we first try the allocation * without __GFP_DIRECT_RECLAIM; if that fails, we punt those * bios we would be blocking to the rescuer workqueue before * we retry with the original gfp_flags. */ if (current->bio_list && (!bio_list_empty(&current->bio_list[0]) || !bio_list_empty(&current->bio_list[1])) && bs->rescue_workqueue) gfp_mask &= ~__GFP_DIRECT_RECLAIM; p = mempool_alloc(bs->bio_pool, gfp_mask); if (!p && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; p = mempool_alloc(bs->bio_pool, gfp_mask); } front_pad = bs->front_pad; inline_vecs = BIO_INLINE_VECS; } if (unlikely(!p)) return NULL; bio = p + front_pad; bio_init(bio, NULL, 0); if (nr_iovecs > inline_vecs) { unsigned long idx = 0; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); if (!bvl && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); } if (unlikely(!bvl)) goto err_free; bio->bi_flags |= idx << BVEC_POOL_OFFSET; } else if (nr_iovecs) { bvl = bio->bi_inline_vecs; } bio->bi_pool = bs; bio->bi_max_vecs = nr_iovecs; bio->bi_io_vec = bvl; return bio; err_free: mempool_free(p, bs->bio_pool); return NULL; } Commit Message: fix unbalanced page refcounting in bio_map_user_iov bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if IO vector has small consecutive buffers belonging to the same page. bio_add_pc_page merges them into one, but the page reference is never dropped. Cc: stable@vger.kernel.org Signed-off-by: Vitaly Mayatskikh <v.mayatskih@gmail.com> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-772
0
22,802
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BlinkTestRunner::DidCommitProvisionalLoad(WebLocalFrame* frame, bool is_new_navigation) { if (!focus_on_next_commit_) return; focus_on_next_commit_ = false; render_view()->GetWebView()->setFocusedFrame(frame); } Commit Message: content: Rename webkit_test_helpers.{cc,h} to blink_test_helpers.{cc,h} Now that webkit/ is gone, we are preparing ourselves for the merge of third_party/WebKit into //blink. BUG=None BUG=content_shell && content_unittests R=avi@chromium.org Review URL: https://codereview.chromium.org/1118183003 Cr-Commit-Position: refs/heads/master@{#328202} CWE ID: CWE-399
0
25,745
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void sctp_inet6_skb_msgname(struct sk_buff *skb, char *msgname, int *addr_len) { union sctp_addr *addr; struct sctphdr *sh; if (!msgname) return; addr = (union sctp_addr *)msgname; sh = sctp_hdr(skb); if (ip_hdr(skb)->version == 4) { addr->v4.sin_family = AF_INET; addr->v4.sin_port = sh->source; addr->v4.sin_addr.s_addr = ip_hdr(skb)->saddr; } else { addr->v6.sin6_family = AF_INET6; addr->v6.sin6_flowinfo = 0; addr->v6.sin6_port = sh->source; addr->v6.sin6_addr = ipv6_hdr(skb)->saddr; if (ipv6_addr_type(&addr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) { addr->v6.sin6_scope_id = sctp_v6_skb_iif(skb); } } *addr_len = sctp_v6_addr_to_user(sctp_sk(skb->sk), addr); } Commit Message: sctp: do not inherit ipv6_{mc|ac|fl}_list from parent SCTP needs fixes similar to 83eaddab4378 ("ipv6/dccp: do not inherit ipv6_mc_list from parent"), otherwise bad things can happen. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
14,842
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void jpc_ft_fwdlift_row(jpc_fix_t *a, int numcols, int parity) { register jpc_fix_t *lptr; register jpc_fix_t *hptr; register int n; int llen; llen = (numcols + 1 - parity) >> 1; if (numcols > 1) { /* Apply the first lifting step. */ lptr = &a[0]; hptr = &a[llen]; if (parity) { hptr[0] -= lptr[0]; ++hptr; } n = numcols - llen - parity - (parity == (numcols & 1)); while (n-- > 0) { hptr[0] -= jpc_fix_asr(lptr[0] + lptr[1], 1); ++hptr; ++lptr; } if (parity == (numcols & 1)) { hptr[0] -= lptr[0]; } /* Apply the second lifting step. */ lptr = &a[0]; hptr = &a[llen]; if (!parity) { lptr[0] += jpc_fix_asr(hptr[0] + 1, 1); ++lptr; } n = llen - (!parity) - (parity != (numcols & 1)); while (n-- > 0) { lptr[0] += jpc_fix_asr(hptr[0] + hptr[1] + 2, 2); ++lptr; ++hptr; } if (parity != (numcols & 1)) { lptr[0] += jpc_fix_asr(hptr[0] + 1, 1); } } else { if (parity) { lptr = &a[0]; lptr[0] = jpc_fix_asl(lptr[0], 1); } } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119
0
9,978
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int jpg_copystreamtofile(FILE *out, jas_stream_t *in) { int c; while ((c = jas_stream_getc(in)) != EOF) { if (fputc(c, out) == EOF) { return -1; } } if (jas_stream_error(in)) { return -1; } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
0
16,804
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rds_send_pong(struct rds_connection *conn, __be16 dport) { struct rds_message *rm; unsigned long flags; int ret = 0; rm = rds_message_alloc(0, GFP_ATOMIC); if (!rm) { ret = -ENOMEM; goto out; } rm->m_daddr = conn->c_faddr; rm->data.op_active = 1; rds_conn_connect_if_down(conn); ret = rds_cong_wait(conn->c_fcong, dport, 1, NULL); if (ret) goto out; spin_lock_irqsave(&conn->c_lock, flags); list_add_tail(&rm->m_conn_item, &conn->c_send_queue); set_bit(RDS_MSG_ON_CONN, &rm->m_flags); rds_message_addref(rm); rm->m_inc.i_conn = conn; rds_message_populate_header(&rm->m_inc.i_hdr, 0, dport, conn->c_next_tx_seq); conn->c_next_tx_seq++; spin_unlock_irqrestore(&conn->c_lock, flags); rds_stats_inc(s_send_queued); rds_stats_inc(s_send_pong); /* schedule the send work on rds_wq */ queue_delayed_work(rds_wq, &conn->c_send_w, 1); rds_message_put(rm); return 0; out: if (rm) rds_message_put(rm); return ret; } Commit Message: RDS: fix race condition when sending a message on unbound socket Sasha's found a NULL pointer dereference in the RDS connection code when sending a message to an apparently unbound socket. The problem is caused by the code checking if the socket is bound in rds_sendmsg(), which checks the rs_bound_addr field without taking a lock on the socket. This opens a race where rs_bound_addr is temporarily set but where the transport is not in rds_bind(), leading to a NULL pointer dereference when trying to dereference 'trans' in __rds_conn_create(). Vegard wrote a reproducer for this issue, so kindly ask him to share if you're interested. I cannot reproduce the NULL pointer dereference using Vegard's reproducer with this patch, whereas I could without. Complete earlier incomplete fix to CVE-2015-6937: 74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection") Cc: David S. Miller <davem@davemloft.net> Cc: stable@vger.kernel.org Reviewed-by: Vegard Nossum <vegard.nossum@oracle.com> Reviewed-by: Sasha Levin <sasha.levin@oracle.com> Acked-by: Santosh Shilimkar <santosh.shilimkar@oracle.com> Signed-off-by: Quentin Casasnovas <quentin.casasnovas@oracle.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
0
6,631
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int32_t PPB_URLLoader_Impl::ReadResponseBody(void* buffer, int32_t bytes_to_read, PP_CompletionCallback callback) { int32_t rv = ValidateCallback(callback); if (rv != PP_OK) return rv; if (!response_info_ || response_info_->body()) return PP_ERROR_FAILED; if (bytes_to_read <= 0 || !buffer) return PP_ERROR_BADARGUMENT; user_buffer_ = static_cast<char*>(buffer); user_buffer_size_ = bytes_to_read; if (!buffer_.empty()) return FillUserBuffer(); if (done_status_ != PP_OK_COMPLETIONPENDING) { user_buffer_ = NULL; user_buffer_size_ = 0; return done_status_; } RegisterCallback(callback); return PP_OK_COMPLETIONPENDING; } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
13,323
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void smp_process_pairing_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); if (smp_command_has_invalid_parameters(p_cb)) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_INVALID_PARAMETERS; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); return; } p_cb->flags |= SMP_PAIR_FLAG_HAVE_PEER_COMM; if (p != NULL) { STREAM_TO_ARRAY(p_cb->remote_commitment, p, BT_OCTET16_LEN); } } Commit Message: Checks the SMP length to fix OOB read Bug: 111937065 Test: manual Change-Id: I330880a6e1671d0117845430db4076dfe1aba688 Merged-In: I330880a6e1671d0117845430db4076dfe1aba688 (cherry picked from commit fceb753bda651c4135f3f93a510e5fcb4c7542b8) CWE ID: CWE-200
0
23,440
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderMessageFilter::OnGetCookies(const GURL& url, const GURL& first_party_for_cookies, IPC::Message* reply_msg) { ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (!policy->CanAccessCookiesForOrigin(render_process_id_, url)) { SendGetCookiesResponse(reply_msg, std::string()); return; } char url_buf[128]; base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); net::URLRequestContext* context = GetRequestContextForURL(url); net::CookieMonster* cookie_monster = context->cookie_store()->GetCookieMonster(); cookie_monster->GetAllCookiesForURLAsync( url, base::Bind(&RenderMessageFilter::CheckPolicyForCookies, this, url, first_party_for_cookies, reply_msg)); } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
0
525
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int mailimf_cfws_parse(const char * message, size_t length, size_t * indx) { size_t cur_token; int has_comment; int r; cur_token = * indx; has_comment = FALSE; while (1) { r = mailimf_cfws_fws_comment_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { if (r == MAILIMF_ERROR_PARSE) break; else return r; } has_comment = TRUE; } if (!has_comment) { r = mailimf_fws_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) return r; } * indx = cur_token; return MAILIMF_NO_ERROR; } Commit Message: Fixed crash #274 CWE ID: CWE-476
0
8,834
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void ipgre_tunnel_unlink(struct ipgre_net *ign, struct ip_tunnel *t) { struct ip_tunnel **tp; for (tp = ipgre_bucket(ign, t); *tp; tp = &(*tp)->next) { if (t == *tp) { spin_lock_bh(&ipgre_lock); *tp = t->next; spin_unlock_bh(&ipgre_lock); break; } } } Commit Message: gre: fix netns vs proto registration ordering GRE protocol receive hook can be called right after protocol addition is done. If netns stuff is not yet initialized, we're going to oops in net_generic(). This is remotely oopsable if ip_gre is compiled as module and packet comes at unfortunate moment of module loading. Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
22,642
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: IntRect PaintLayerScrollableArea::RectForVerticalScrollbar( const IntRect& border_box_rect) const { if (!HasVerticalScrollbar()) return IntRect(); const IntRect& scroll_corner = ScrollCornerRect(); return IntRect( VerticalScrollbarStart(border_box_rect.X(), border_box_rect.MaxX()), border_box_rect.Y() + GetLayoutBox()->BorderTop().ToInt(), VerticalScrollbar()->ScrollbarThickness(), border_box_rect.Height() - (GetLayoutBox()->BorderTop() + GetLayoutBox()->BorderBottom()) .ToInt() - scroll_corner.Height()); } Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer Bug: 927560 Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4 Reviewed-on: https://chromium-review.googlesource.com/c/1452701 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Commit-Queue: Mason Freed <masonfreed@chromium.org> Cr-Commit-Position: refs/heads/master@{#628942} CWE ID: CWE-79
0
22,321
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void echo_move_back_col(struct n_tty_data *ldata) { add_echo_byte(ECHO_OP_START, ldata); add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata); } Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <jslaby@suse.cz> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Jiri Slaby <jslaby@suse.cz> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Alan Cox <alan@lxorguk.ukuu.org.uk> Cc: <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-362
0
19,659
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gst_qtdemux_find_index (GstQTDemux * qtdemux, QtDemuxStream * str, guint64 media_time) { guint32 i; if (str->n_samples == 0) return 0; for (i = 0; i < str->n_samples; i++) { if (str->samples[i].timestamp > media_time) { /* first sample after media_time, we need the previous one */ return (i == 0 ? 0 : i - 1); } } return str->n_samples - 1; } Commit Message: CWE ID: CWE-119
0
2,286
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void QQuickWebViewFlickablePrivate::onComponentComplete() { Q_Q(QQuickWebView); ASSERT(!flickProvider); flickProvider = new QtFlickProvider(q, pageView.data()); const QQuickWebViewExperimental* experimental = q->experimental(); QObject::connect(flickProvider, SIGNAL(contentWidthChanged()), experimental, SIGNAL(contentWidthChanged())); QObject::connect(flickProvider, SIGNAL(contentHeightChanged()), experimental, SIGNAL(contentHeightChanged())); QObject::connect(flickProvider, SIGNAL(contentXChanged()), experimental, SIGNAL(contentXChanged())); QObject::connect(flickProvider, SIGNAL(contentYChanged()), experimental, SIGNAL(contentYChanged())); interactionEngine.reset(new QtViewportInteractionEngine(q, pageView.data(), flickProvider)); pageView->eventHandler()->setViewportInteractionEngine(interactionEngine.data()); QObject::connect(interactionEngine.data(), SIGNAL(contentSuspendRequested()), q, SLOT(_q_suspend())); QObject::connect(interactionEngine.data(), SIGNAL(contentResumeRequested()), q, SLOT(_q_resume())); QObject::connect(interactionEngine.data(), SIGNAL(contentWasMoved(const QPointF&)), q, SLOT(_q_commitPositionChange(const QPointF&))); QObject::connect(interactionEngine.data(), SIGNAL(contentWasScaled()), q, SLOT(_q_commitScaleChange())); _q_resume(); if (loadSuccessDispatchIsPending) { QQuickWebViewPrivate::loadDidSucceed(); loadSuccessDispatchIsPending = false; } _q_onVisibleChanged(); QQuickWebViewPrivate::onComponentComplete(); } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189
0
885
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: tracing_cpumask_read(struct file *filp, char __user *ubuf, size_t count, loff_t *ppos) { struct trace_array *tr = file_inode(filp)->i_private; char *mask_str; int len; len = snprintf(NULL, 0, "%*pb\n", cpumask_pr_args(tr->tracing_cpumask)) + 1; mask_str = kmalloc(len, GFP_KERNEL); if (!mask_str) return -ENOMEM; len = snprintf(mask_str, len, "%*pb\n", cpumask_pr_args(tr->tracing_cpumask)); if (len >= count) { count = -EINVAL; goto out_err; } count = simple_read_from_buffer(ubuf, count, ppos, mask_str, len); out_err: kfree(mask_str); return count; } 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
0
23,371
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: poly_overlap(PG_FUNCTION_ARGS) { POLYGON *polya = PG_GETARG_POLYGON_P(0); POLYGON *polyb = PG_GETARG_POLYGON_P(1); bool result; /* Quick check by bounding box */ result = (polya->npts > 0 && polyb->npts > 0 && box_ov(&polya->boundbox, &polyb->boundbox)) ? true : false; /* * Brute-force algorithm - try to find intersected edges, if so then * polygons are overlapped else check is one polygon inside other or not * by testing single point of them. */ if (result) { int ia, ib; LSEG sa, sb; /* Init first of polya's edge with last point */ sa.p[0] = polya->p[polya->npts - 1]; result = false; for (ia = 0; ia < polya->npts && result == false; ia++) { /* Second point of polya's edge is a current one */ sa.p[1] = polya->p[ia]; /* Init first of polyb's edge with last point */ sb.p[0] = polyb->p[polyb->npts - 1]; for (ib = 0; ib < polyb->npts && result == false; ib++) { sb.p[1] = polyb->p[ib]; result = lseg_intersect_internal(&sa, &sb); sb.p[0] = sb.p[1]; } /* * move current endpoint to the first point of next edge */ sa.p[0] = sa.p[1]; } if (result == false) { result = (point_inside(polya->p, polyb->npts, polyb->p) || point_inside(polyb->p, polya->npts, polya->p)); } } /* * Avoid leaking memory for toasted inputs ... needed for rtree indexes */ PG_FREE_IF_COPY(polya, 0); PG_FREE_IF_COPY(polyb, 1); PG_RETURN_BOOL(result); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
0
26,453
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-310
1
26,709
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static size_t rdfa_init_base( rdfacontext* context, char** working_buffer, size_t* working_buffer_size, char* temp_buffer, size_t bytes_read) { char* head_end = NULL; size_t offset = context->wb_position; size_t needed_size = (offset + bytes_read) - *working_buffer_size; if(needed_size > 0) { size_t temp_buffer_size = sizeof(char) * READ_BUFFER_SIZE; if((size_t)needed_size > temp_buffer_size) temp_buffer_size += needed_size; *working_buffer_size += temp_buffer_size; *working_buffer = (char*)realloc(*working_buffer, *working_buffer_size + 1); } memmove(*working_buffer + offset, temp_buffer, bytes_read); *(*working_buffer + offset + bytes_read) = '\0'; head_end = strstr(*working_buffer, "</head>"); if(head_end == NULL) head_end = strstr(*working_buffer, "</HEAD>"); context->wb_position += bytes_read; if(head_end == NULL) return bytes_read; if(head_end != NULL) { char* base_start = strstr(*working_buffer, "<base "); if(base_start == NULL) base_start = strstr(*working_buffer, "<BASE "); if(base_start != NULL) { char* href_start = strstr(base_start, "href="); char sep = href_start[5]; char* uri_start = href_start + 6; char* uri_end = strchr(uri_start, sep); if((uri_start != NULL) && (uri_end != NULL)) { if(*uri_start != sep) { size_t uri_size = uri_end - uri_start; char* temp_uri = (char*)malloc(sizeof(char) * uri_size + 1); char* cleaned_base; strncpy(temp_uri, uri_start, uri_size); temp_uri[uri_size] = '\0'; cleaned_base = rdfa_iri_get_base(temp_uri); context->current_object_resource = rdfa_replace_string( context->current_object_resource, cleaned_base); context->base = rdfa_replace_string(context->base, cleaned_base); free(cleaned_base); free(temp_uri); } } } } return bytes_read; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
0
9,839
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int32_t readSize(off64_t offset, const sp<DataSource> &DataSource, uint8_t *numOfBytes) { uint32_t size = 0; uint8_t data; bool moreData = true; *numOfBytes = 0; while (moreData) { if (DataSource->readAt(offset, &data, 1) < 1) { return -1; } offset ++; moreData = (data >= 128) ? true : false; size = (size << 7) | (data & 0x7f); // Take last 7 bits (*numOfBytes) ++; } return size; } Commit Message: Skip track if verification fails Bug: 62187433 Test: ran poc, CTS Change-Id: Ib9b0b6de88d046d8149e9ea5073d6c40ffec7b0c (cherry picked from commit ef8c7830d838d877e6b37b75b47294b064c79397) CWE ID:
0
21,840
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int vcc_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { struct sock *sk = sock->sk; DEFINE_WAIT(wait); struct atm_vcc *vcc; struct sk_buff *skb; int eff, error; const void __user *buff; int size; lock_sock(sk); if (sock->state != SS_CONNECTED) { error = -ENOTCONN; goto out; } if (m->msg_name) { error = -EISCONN; goto out; } if (m->msg_iovlen != 1) { error = -ENOSYS; /* fix this later @@@ */ goto out; } buff = m->msg_iov->iov_base; size = m->msg_iov->iov_len; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); goto out; } if (!size) { error = 0; goto out; } if (size < 0 || size > vcc->qos.txtp.max_sdu) { error = -EMSGSIZE; goto out; } eff = (size+3) & ~3; /* align to word boundary */ prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); error = 0; while (!(skb = alloc_tx(vcc, eff))) { if (m->msg_flags & MSG_DONTWAIT) { error = -EAGAIN; break; } schedule(); if (signal_pending(current)) { error = -ERESTARTSYS; break; } if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } finish_wait(sk_sleep(sk), &wait); if (error) goto out; skb->dev = NULL; /* for paths shared with net_device interfaces */ ATM_SKB(skb)->atm_options = vcc->atm_options; if (copy_from_user(skb_put(skb, size), buff, size)) { kfree_skb(skb); error = -EFAULT; goto out; } if (eff != size) memset(skb->data + size, 0, eff-size); error = vcc->dev->ops->send(vcc, skb); error = error ? error : size; out: release_sock(sk); return error; } Commit Message: atm: update msg_namelen in vcc_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about vcc_recvmsg() not filling the msg_name in case it was set. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
23,266
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void FS_CheckPak0( void ) { searchpath_t *path; pack_t *curpack; qboolean founddemo = qfalse; unsigned int foundPak = 0; for( path = fs_searchpaths; path; path = path->next ) { const char* pakBasename = path->pack->pakBasename; if(!path->pack) continue; curpack = path->pack; if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH ) && !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH )) { if(curpack->checksum == DEMO_PAK0_CHECKSUM) founddemo = qtrue; } else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH ) && strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 ) && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1) { if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] ) { if(pakBasename[3] == '0') { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n" "is not correct. Please re-copy pak0.pk3 from your\n" "legitimate RTCW CDROM.\n" "**************************************************\n\n\n", curpack->checksum ); Com_Error(ERR_FATAL, NULL); } /* else { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n" "is not correct. Please re-install the point release\n" "**************************************************\n\n\n", pakBasename[3]-'0', curpack->checksum ); } */ } foundPak |= 1<<(pakBasename[3]-'0'); } else { int index; for(index = 0; index < ARRAY_LEN(pak_checksums); index++) { if(curpack->checksum == pak_checksums[index]) { Com_Printf("\n\n" "**************************************************\n" "WARNING: %s is renamed pak file %s%cpak%d.pk3\n" "Running in standalone mode won't work\n" "Please rename, or remove this file\n" "**************************************************\n\n\n", curpack->pakFilename, BASEGAME, PATH_SEP, index); foundPak |= 0x80000000; } } } } if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME)) { Cvar_Set("com_standalone", "1"); } else Cvar_Set("com_standalone", "0"); if(!com_standalone->integer) { if(!(foundPak & 0x01)) { if(founddemo) { Com_Printf( "\n\n" "**************************************************\n" "WARNING: It looks like you're using pak0.pk3\n" "from the demo. This may work fine, but it is not\n" "guaranteed or supported.\n" "**************************************************\n\n\n" ); foundPak |= 0x01; } } } if(!com_standalone->integer && (foundPak & 0x01) != 0x01) { char errorText[MAX_STRING_CHARS] = ""; if((foundPak & 0x01) != 0x01) { Q_strcat(errorText, sizeof(errorText), "\n\n\"pak0.pk3\" is missing. Please copy it\n" "from your legitimate RTCW CDROM.\n\n"); } Q_strcat(errorText, sizeof(errorText), va("Also check that your iortcw executable is in\n" "the correct place and that every file\n" "in the \"%s\" directory is present and readable.\n\n", BASEGAME)); Com_Error(ERR_FATAL, "%s", errorText); } if(!founddemo) FS_CheckSPPaks(); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
0
298
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ProfilingProcessHost::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); content::RenderProcessHost* host = content::Source<content::RenderProcessHost>(source).ptr(); if (host == profiled_renderer_ && (type == content::NOTIFICATION_RENDERER_PROCESS_TERMINATED || type == content::NOTIFICATION_RENDERER_PROCESS_CLOSED)) { DCHECK_EQ(mode(), Mode::kRendererSampling); profiled_renderer_ = nullptr; } if (type == content::NOTIFICATION_RENDERER_PROCESS_CREATED && ShouldProfileNewRenderer(host)) { if (mode() == Mode::kRendererSampling) { profiled_renderer_ = host; } ProfilingClientBinder client(host); content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::IO) ->PostTask( FROM_HERE, base::BindOnce(&ProfilingProcessHost::AddClientToProfilingService, base::Unretained(this), client.take(), base::GetProcId(host->GetHandle()), profiling::mojom::ProcessType::RENDERER)); } } Commit Message: [Reland #1] Add Android OOP HP end-to-end tests. The original CL added a javatest and its dependencies to the apk_under_test. This causes the dependencies to be stripped from the instrumentation_apk, which causes issue. This CL updates the build configuration so that the javatest and its dependencies are only added to the instrumentation_apk. This is a reland of e0b4355f0651adb1ebc2c513dc4410471af712f5 Original change's description: > Add Android OOP HP end-to-end tests. > > This CL has three components: > 1) The bulk of the logic in OOP HP was refactored into ProfilingTestDriver. > 2) Adds a java instrumentation test, along with a JNI shim that forwards into > ProfilingTestDriver. > 3) Creates a new apk: chrome_public_apk_for_test that contains the same > content as chrome_public_apk, as well as native files needed for (2). > chrome_public_apk_test now targets chrome_public_apk_for_test instead of > chrome_public_apk. > > Other ideas, discarded: > * Originally, I attempted to make the browser_tests target runnable on > Android. The primary problem is that native test harness cannot fork > or spawn processes. This is difficult to solve. > > More details on each of the components: > (1) ProfilingTestDriver > * The TracingController test was migrated to use ProfilingTestDriver, but the > write-to-file test was left as-is. The latter behavior will likely be phased > out, but I'll clean that up in a future CL. > * gtest isn't supported for Android instrumentation tests. ProfilingTestDriver > has a single function RunTest that returns a 'bool' indicating success. On > failure, the class uses LOG(ERROR) to print the nature of the error. This will > cause the error to be printed out on browser_test error. On instrumentation > test failure, the error will be forwarded to logcat, which is available on all > infra bot test runs. > (2) Instrumentation test > * For now, I only added a single test for the "browser" mode. Furthermore, I'm > only testing the start with command-line path. > (3) New apk > * libchromefortest is a new shared library that contains all content from > libchrome, but also contains native sources for the JNI shim. > * chrome_public_apk_for_test is a new apk that contains all content from > chrome_public_apk, but uses a single shared library libchromefortest rather > than libchrome. This also contains java sources for the JNI shim. > * There is no way to just add a second shared library to chrome_public_apk > that just contains the native sources from the JNI shim without causing ODR > issues. > * chrome_public_test_apk now has apk_under_test = chrome_public_apk_for_test. > * There is no way to add native JNI sources as a shared library to > chrome_public_test_apk without causing ODR issues. > > Finally, this CL drastically increases the timeout to wait for native > initialization. The previous timeout was 2 * > CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL, which flakily failed for this test. > This suggests that this step/timeout is generally flaky. I increased the timeout > to 20 * CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL. > > Bug: 753218 > Change-Id: Ic224b7314fff57f1770a4048aa5753f54e040b55 > Reviewed-on: https://chromium-review.googlesource.com/770148 > Commit-Queue: Erik Chen <erikchen@chromium.org> > Reviewed-by: John Budorick <jbudorick@chromium.org> > Reviewed-by: Brett Wilson <brettw@chromium.org> > Cr-Commit-Position: refs/heads/master@{#517541} Bug: 753218 TBR: brettw@chromium.org Change-Id: Ic6aafb34c2467253f75cc85da48200d19f3bc9af Reviewed-on: https://chromium-review.googlesource.com/777697 Commit-Queue: Erik Chen <erikchen@chromium.org> Reviewed-by: John Budorick <jbudorick@chromium.org> Cr-Commit-Position: refs/heads/master@{#517850} CWE ID: CWE-416
0
8,936
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: net::Error NavigationRequest::CheckCSPDirectives( RenderFrameHostImpl* parent, bool is_redirect, bool url_upgraded_after_redirect, bool is_response_check, CSPContext::CheckCSPDisposition disposition) { bool navigate_to_allowed = IsAllowedByCSPDirective( initiator_csp_context_.get(), CSPDirective::NavigateTo, is_redirect, url_upgraded_after_redirect, is_response_check, disposition); bool frame_src_allowed = true; if (parent) { frame_src_allowed = IsAllowedByCSPDirective( parent, CSPDirective::FrameSrc, is_redirect, url_upgraded_after_redirect, is_response_check, disposition); } if (navigate_to_allowed && frame_src_allowed) return net::OK; if (!frame_src_allowed) return net::ERR_BLOCKED_BY_CLIENT; return net::ERR_ABORTED; } Commit Message: Use an opaque URL rather than an empty URL for request's site for cookies. Apparently this makes a big difference to the cookie settings backend. Bug: 881715 Change-Id: Id87fa0c6a858bae6a3f8fff4d6af3f974b00d5e4 Reviewed-on: https://chromium-review.googlesource.com/1212846 Commit-Queue: Mike West <mkwst@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#589512} CWE ID: CWE-20
0
19,453
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb, const struct iov_iter *iter, loff_t offset) { int seg; int i; unsigned blocksize_mask = root->sectorsize - 1; ssize_t retval = -EINVAL; if (offset & blocksize_mask) goto out; if (iov_iter_alignment(iter) & blocksize_mask) goto out; /* If this is a write we don't need to check anymore */ if (iov_iter_rw(iter) == WRITE) return 0; /* * Check to make sure we don't have duplicate iov_base's in this * iovec, if so return EINVAL, otherwise we'll get csum errors * when reading back. */ for (seg = 0; seg < iter->nr_segs; seg++) { for (i = seg + 1; i < iter->nr_segs; i++) { if (iter->iov[seg].iov_base == iter->iov[i].iov_base) goto out; } } retval = 0; out: return retval; } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: stable@vger.kernel.org Signed-off-by: Filipe Manana <fdmanana@suse.com> CWE ID: CWE-200
0
29,633
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int au1200fb_init_fbinfo(struct au1200fb_device *fbdev) { struct fb_info *fbi = fbdev->fb_info; int bpp; fbi->fbops = &au1200fb_fb_ops; bpp = winbpp(win->w[fbdev->plane].mode_winctrl1); /* Copy monitor specs from panel data */ /* fixme: we're setting up LCD controller windows, so these dont give a damn as to what the monitor specs are (the panel itself does, but that isn't done here...so maybe need a generic catchall monitor setting??? */ memcpy(&fbi->monspecs, &panel->monspecs, sizeof(struct fb_monspecs)); /* We first try the user mode passed in argument. If that failed, * or if no one has been specified, we default to the first mode of the * panel list. Note that after this call, var data will be set */ if (!fb_find_mode(&fbi->var, fbi, NULL, /* drv_info.opt_mode, */ fbi->monspecs.modedb, fbi->monspecs.modedb_len, fbi->monspecs.modedb, bpp)) { print_err("Cannot find valid mode for panel %s", panel->name); return -EFAULT; } fbi->pseudo_palette = kcalloc(16, sizeof(u32), GFP_KERNEL); if (!fbi->pseudo_palette) { return -ENOMEM; } if (fb_alloc_cmap(&fbi->cmap, AU1200_LCD_NBR_PALETTE_ENTRIES, 0) < 0) { print_err("Fail to allocate colormap (%d entries)", AU1200_LCD_NBR_PALETTE_ENTRIES); kfree(fbi->pseudo_palette); return -EFAULT; } strncpy(fbi->fix.id, "AU1200", sizeof(fbi->fix.id)); fbi->fix.smem_start = fbdev->fb_phys; fbi->fix.smem_len = fbdev->fb_len; fbi->fix.type = FB_TYPE_PACKED_PIXELS; fbi->fix.xpanstep = 0; fbi->fix.ypanstep = 0; fbi->fix.mmio_start = 0; fbi->fix.mmio_len = 0; fbi->fix.accel = FB_ACCEL_NONE; fbi->screen_base = (char __iomem *) fbdev->fb_mem; au1200fb_update_fbinfo(fbi); return 0; } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <nico@ngolde.de> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org. CWE ID: CWE-119
0
26,329
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: NavigationPolicy FrameLoader::ShouldContinueForRedirectNavigationPolicy( const ResourceRequest& request, const SubstituteData& substitute_data, DocumentLoader* loader, ContentSecurityPolicyDisposition should_check_main_world_content_security_policy, NavigationType type, NavigationPolicy policy, FrameLoadType frame_load_type, bool is_client_redirect, HTMLFormElement* form) { Settings* settings = frame_->GetSettings(); MaybeCheckCSP(request, type, frame_, policy, should_check_main_world_content_security_policy == kCheckContentSecurityPolicy, settings && settings->GetBrowserSideNavigationEnabled(), ContentSecurityPolicy::CheckHeaderType::kCheckReportOnly); return ShouldContinueForNavigationPolicy( request, nullptr, // origin_document substitute_data, loader, should_check_main_world_content_security_policy, type, policy, frame_load_type, is_client_redirect, WebTriggeringEventInfo::kNotFromEvent, form); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Nate Chapin <japhet@chromium.org> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362
0
28,213
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Ins_ROFF( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_Off; exc->func_round = (TT_Round_Func)Round_None; } Commit Message: CWE ID: CWE-476
0
15,795
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void MaybeActivateProfile() { if (!profile_to_activate_) return; auto i = launched_profiles_.begin(); for (; i != launched_profiles_.end(); ++i) { if (opened_profiles_.find(*i) == opened_profiles_.end()) return; } base::PostTask(FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ProfileLaunchObserver::ActivateProfile, base::Unretained(this))); registrar_.RemoveAll(); BrowserList::RemoveObserver(this); } Commit Message: Prevent regular mode session startup pref type turning to default. When user loses past session tabs of regular mode after invoking a new window from the incognito mode. This was happening because the SessionStartUpPref type was being set to default, from last, for regular user mode. This was happening in the RestoreIfNecessary method where the restoration was taking place for users whose SessionStartUpPref type was set to last. The fix was to make the protocol of changing the pref type to default more explicit to incognito users and not regular users of pref type last. Bug: 481373 Change-Id: I96efb4cf196949312181c83c6dcd45986ddded13 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1774441 Reviewed-by: Tommy Martino <tmartino@chromium.org> Reviewed-by: Ramin Halavati <rhalavati@chromium.org> Commit-Queue: Rohit Agarwal <roagarwal@chromium.org> Cr-Commit-Position: refs/heads/master@{#691726} CWE ID: CWE-79
0
9,942
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void set_current_blocked(sigset_t *newset) { sigdelsetmask(newset, sigmask(SIGKILL) | sigmask(SIGSTOP)); __set_current_blocked(newset); } Commit Message: kernel/signal.c: stop info leak via the tkill and the tgkill syscalls This fixes a kernel memory contents leak via the tkill and tgkill syscalls for compat processes. This is visible in the siginfo_t->_sifields._rt.si_sigval.sival_ptr field when handling signals delivered from tkill. The place of the infoleak: int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from) { ... put_user_ex(ptr_to_compat(from->si_ptr), &to->si_ptr); ... } Signed-off-by: Emese Revfy <re.emese@gmail.com> Reviewed-by: PaX Team <pageexec@freemail.hu> Signed-off-by: Kees Cook <keescook@chromium.org> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Serge Hallyn <serge.hallyn@canonical.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-399
0
10,392
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static CURLcode nss_fail_connect(struct ssl_connect_data *connssl, struct Curl_easy *data, CURLcode curlerr) { PRErrorCode err = 0; if(is_nss_error(curlerr)) { /* read NSPR error code */ err = PR_GetError(); if(is_cc_error(err)) curlerr = CURLE_SSL_CERTPROBLEM; /* print the error number and error string */ infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err)); /* print a human-readable message describing the error if available */ nss_print_error_message(data, err); } /* cleanup on connection failure */ Curl_llist_destroy(connssl->obj_list, NULL); connssl->obj_list = NULL; return curlerr; } Commit Message: nss: refuse previously loaded certificate from file ... when we are not asked to use a certificate from file CWE ID: CWE-287
0
4,044
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int _nfs4_proc_link(struct inode *inode, struct inode *dir, struct qstr *name) { struct nfs_server *server = NFS_SERVER(inode); struct nfs4_link_arg arg = { .fh = NFS_FH(inode), .dir_fh = NFS_FH(dir), .name = name, .bitmask = server->attr_bitmask, }; struct nfs4_link_res res = { .server = server, .label = NULL, }; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LINK], .rpc_argp = &arg, .rpc_resp = &res, }; int status = -ENOMEM; res.fattr = nfs_alloc_fattr(); if (res.fattr == NULL) goto out; res.label = nfs4_label_alloc(server, GFP_KERNEL); if (IS_ERR(res.label)) { status = PTR_ERR(res.label); goto out; } arg.bitmask = nfs4_bitmask(server, res.label); status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1); if (!status) { update_changeattr(dir, &res.cinfo); status = nfs_post_op_update_inode(inode, res.fattr); if (!status) nfs_setsecurity(inode, res.fattr, res.label); } nfs4_label_free(res.label); out: nfs_free_fattr(res.fattr); return status; } Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client ---Steps to Reproduce-- <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) <nfs-client> # mount -t nfs nfs-server:/nfs/ /mnt/ # ll /mnt/*/ <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) # service nfs restart <nfs-client> # ll /mnt/*/ --->>>>> oops here [ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null) [ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0 [ 5123.104131] Oops: 0000 [#1] [ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd] [ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214 [ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014 [ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000 [ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246 [ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240 [ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908 [ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000 [ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800 [ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240 [ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000 [ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0 [ 5123.112888] Stack: [ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000 [ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6 [ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800 [ 5123.115264] Call Trace: [ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4] [ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4] [ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4] [ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0 [ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70 [ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33 [ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.122308] RSP <ffff88005877fdb8> [ 5123.122942] CR2: 0000000000000000 Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops") Cc: stable@vger.kernel.org # v3.13+ Signed-off-by: Kinglong Mee <kinglongmee@gmail.com> Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com> CWE ID:
0
28,176
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: renderTable(struct table *t, int max_width, struct html_feed_environ *h_env) { int i, j, w, r, h; Str renderbuf; short new_tabwidth[MAXCOL] = { 0 }; #ifdef MATRIX int itr; VEC *newwidth; MAT *mat, *minv; PERM *pivot; #endif /* MATRIX */ int width; int rulewidth; Str vrulea = NULL, vruleb = NULL, vrulec = NULL; #ifdef ID_EXT Str idtag; #endif /* ID_EXT */ t->total_height = 0; if (t->maxcol < 0) { make_caption(t, h_env); return; } if (t->sloppy_width > max_width) max_width = t->sloppy_width; rulewidth = table_rule_width(t); max_width -= table_border_width(t); if (rulewidth > 1) max_width = floor_at_intervals(max_width, rulewidth); if (max_width < rulewidth) max_width = rulewidth; #define MAX_TABWIDTH 10000 if (max_width > MAX_TABWIDTH) max_width = MAX_TABWIDTH; check_maximum_width(t); #ifdef MATRIX if (t->maxcol == 0) { if (t->tabwidth[0] > max_width) t->tabwidth[0] = max_width; if (t->total_width > 0) t->tabwidth[0] = max_width; else if (t->fixed_width[0] > 0) t->tabwidth[0] = t->fixed_width[0]; if (t->tabwidth[0] < t->minimum_width[0]) t->tabwidth[0] = t->minimum_width[0]; } else { set_table_matrix(t, max_width); itr = 0; mat = m_get(t->maxcol + 1, t->maxcol + 1); pivot = px_get(t->maxcol + 1); newwidth = v_get(t->maxcol + 1); minv = m_get(t->maxcol + 1, t->maxcol + 1); do { m_copy(t->matrix, mat); LUfactor(mat, pivot); LUsolve(mat, pivot, t->vector, newwidth); LUinverse(mat, pivot, minv); #ifdef TABLE_DEBUG set_integered_width(t, newwidth->ve, new_tabwidth); fprintf(stderr, "itr=%d\n", itr); fprintf(stderr, "max_width=%d\n", max_width); fprintf(stderr, "minimum : "); for (i = 0; i <= t->maxcol; i++) fprintf(stderr, "%2d ", t->minimum_width[i]); fprintf(stderr, "\nfixed : "); for (i = 0; i <= t->maxcol; i++) fprintf(stderr, "%2d ", t->fixed_width[i]); fprintf(stderr, "\ndecided : "); for (i = 0; i <= t->maxcol; i++) fprintf(stderr, "%2d ", new_tabwidth[i]); fprintf(stderr, "\n"); #endif /* TABLE_DEBUG */ itr++; } while (check_table_width(t, newwidth->ve, minv, itr)); set_integered_width(t, newwidth->ve, new_tabwidth); check_minimum_width(t, new_tabwidth); v_free(newwidth); px_free(pivot); m_free(mat); m_free(minv); m_free(t->matrix); v_free(t->vector); for (i = 0; i <= t->maxcol; i++) { t->tabwidth[i] = new_tabwidth[i]; } } #else /* not MATRIX */ set_table_width(t, new_tabwidth, max_width); for (i = 0; i <= t->maxcol; i++) { t->tabwidth[i] = new_tabwidth[i]; } #endif /* not MATRIX */ check_minimum_width(t, t->tabwidth); for (i = 0; i <= t->maxcol; i++) t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth); renderCoTable(t, h_env->limit); for (i = 0; i <= t->maxcol; i++) { for (j = 0; j <= t->maxrow; j++) { check_row(t, j); if (t->tabattr[j][i] & HTT_Y) continue; do_refill(t, j, i, h_env->limit); } } check_minimum_width(t, t->tabwidth); t->total_width = 0; for (i = 0; i <= t->maxcol; i++) { t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth); t->total_width += t->tabwidth[i]; } t->total_width += table_border_width(t); check_table_height(t); for (i = 0; i <= t->maxcol; i++) { for (j = 0; j <= t->maxrow; j++) { TextLineList *l; int k; if ((t->tabattr[j][i] & HTT_Y) || (t->tabattr[j][i] & HTT_TOP) || (t->tabdata[j][i] == NULL)) continue; h = t->tabheight[j]; for (k = j + 1; k <= t->maxrow; k++) { if (!(t->tabattr[k][i] & HTT_Y)) break; h += t->tabheight[k]; switch (t->border_mode) { case BORDER_THIN: case BORDER_THICK: case BORDER_NOWIN: h += 1; break; } } h -= t->tabdata[j][i]->nitem; if (t->tabattr[j][i] & HTT_MIDDLE) h /= 2; if (h <= 0) continue; l = newTextLineList(); for (k = 0; k < h; k++) pushTextLine(l, newTextLine(NULL, 0)); t->tabdata[j][i] = appendGeneralList((GeneralList *)l, t->tabdata[j][i]); } } /* table output */ width = t->total_width; make_caption(t, h_env); HTMLlineproc1("<pre for_table>", h_env); #ifdef ID_EXT if (t->id != NULL) { idtag = Sprintf("<_id id=\"%s\">", html_quote((t->id)->ptr)); HTMLlineproc1(idtag->ptr, h_env); } #endif /* ID_EXT */ switch (t->border_mode) { case BORDER_THIN: case BORDER_THICK: renderbuf = Strnew(); print_sep(t, -1, T_TOP, t->maxcol, renderbuf); push_render_image(renderbuf, width, t->total_width, h_env); t->total_height += 1; break; } vruleb = Strnew(); switch (t->border_mode) { case BORDER_THIN: case BORDER_THICK: vrulea = Strnew(); vrulec = Strnew(); push_symbol(vrulea, TK_VERTICALBAR(t->border_mode), symbol_width, 1); for (i = 0; i < t->cellpadding; i++) { Strcat_char(vrulea, ' '); Strcat_char(vruleb, ' '); Strcat_char(vrulec, ' '); } push_symbol(vrulec, TK_VERTICALBAR(t->border_mode), symbol_width, 1); case BORDER_NOWIN: push_symbol(vruleb, TK_VERTICALBAR(BORDER_THIN), symbol_width, 1); for (i = 0; i < t->cellpadding; i++) Strcat_char(vruleb, ' '); break; case BORDER_NONE: for (i = 0; i < t->cellspacing; i++) Strcat_char(vruleb, ' '); } for (r = 0; r <= t->maxrow; r++) { for (h = 0; h < t->tabheight[r]; h++) { renderbuf = Strnew(); if (t->border_mode == BORDER_THIN || t->border_mode == BORDER_THICK) Strcat(renderbuf, vrulea); #ifdef ID_EXT if (t->tridvalue[r] != NULL && h == 0) { idtag = Sprintf("<_id id=\"%s\">", html_quote((t->tridvalue[r])->ptr)); Strcat(renderbuf, idtag); } #endif /* ID_EXT */ for (i = 0; i <= t->maxcol; i++) { check_row(t, r); #ifdef ID_EXT if (t->tabidvalue[r][i] != NULL && h == 0) { idtag = Sprintf("<_id id=\"%s\">", html_quote((t->tabidvalue[r][i])->ptr)); Strcat(renderbuf, idtag); } #endif /* ID_EXT */ if (!(t->tabattr[r][i] & HTT_X)) { w = t->tabwidth[i]; for (j = i + 1; j <= t->maxcol && (t->tabattr[r][j] & HTT_X); j++) w += t->tabwidth[j] + t->cellspacing; if (t->tabattr[r][i] & HTT_Y) { for (j = r - 1; j >= 0 && t->tabattr[j] && (t->tabattr[j][i] & HTT_Y); j--) ; print_item(t, j, i, w, renderbuf); } else print_item(t, r, i, w, renderbuf); } if (i < t->maxcol && !(t->tabattr[r][i + 1] & HTT_X)) Strcat(renderbuf, vruleb); } switch (t->border_mode) { case BORDER_THIN: case BORDER_THICK: Strcat(renderbuf, vrulec); t->total_height += 1; break; } push_render_image(renderbuf, width, t->total_width, h_env); } if (r < t->maxrow && t->border_mode != BORDER_NONE) { renderbuf = Strnew(); print_sep(t, r, T_MIDDLE, t->maxcol, renderbuf); push_render_image(renderbuf, width, t->total_width, h_env); } t->total_height += t->tabheight[r]; } switch (t->border_mode) { case BORDER_THIN: case BORDER_THICK: renderbuf = Strnew(); print_sep(t, t->maxrow, T_BOTTOM, t->maxcol, renderbuf); push_render_image(renderbuf, width, t->total_width, h_env); t->total_height += 1; break; } if (t->total_height == 0) { renderbuf = Strnew_charp(" "); t->total_height++; t->total_width = 1; push_render_image(renderbuf, 1, t->total_width, h_env); } HTMLlineproc1("</pre>", h_env); } Commit Message: Prevent negative indent value in feed_table_block_tag() Bug-Debian: https://github.com/tats/w3m/issues/88 CWE ID: CWE-835
0
13,703
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GLES2DecoderImpl::DoCopySubTextureCHROMIUM( GLuint source_id, GLint source_level, GLenum dest_target, GLuint dest_id, GLint dest_level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLboolean unpack_flip_y, GLboolean unpack_premultiply_alpha, GLboolean unpack_unmultiply_alpha) { TRACE_EVENT0("gpu", "GLES2DecoderImpl::DoCopySubTextureCHROMIUM"); static const char kFunctionName[] = "glCopySubTextureCHROMIUM"; CopySubTextureHelper(kFunctionName, source_id, source_level, dest_target, dest_id, dest_level, xoffset, yoffset, x, y, width, height, unpack_flip_y, unpack_premultiply_alpha, unpack_unmultiply_alpha, GL_FALSE /* dither */); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
26,049
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ProfileSyncService::GetBackendMigratorForTest() { return migrator_.get(); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
0
3,230
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: htmlParseHTMLName(htmlParserCtxtPtr ctxt) { int i = 0; xmlChar loc[HTML_PARSER_BUFFER_SIZE]; if (!IS_ASCII_LETTER(CUR) && (CUR != '_') && (CUR != ':') && (CUR != '.')) return(NULL); while ((i < HTML_PARSER_BUFFER_SIZE) && ((IS_ASCII_LETTER(CUR)) || (IS_ASCII_DIGIT(CUR)) || (CUR == ':') || (CUR == '-') || (CUR == '_') || (CUR == '.'))) { if ((CUR >= 'A') && (CUR <= 'Z')) loc[i] = CUR + 0x20; else loc[i] = CUR; i++; NEXT; } return(xmlDictLookup(ctxt->dict, loc, i)); } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <scottmg@chromium.org> Commit-Queue: Dominic Cooney <dominicc@chromium.org> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787
0
12,207
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) { struct mempolicy *mpol = NULL; if (sbinfo->mpol) { spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */ mpol = sbinfo->mpol; mpol_get(mpol); spin_unlock(&sbinfo->stat_lock); } return mpol; } Commit Message: tmpfs: fix use-after-free of mempolicy object The tmpfs remount logic preserves filesystem mempolicy if the mpol=M option is not specified in the remount request. A new policy can be specified if mpol=M is given. Before this patch remounting an mpol bound tmpfs without specifying mpol= mount option in the remount request would set the filesystem's mempolicy object to a freed mempolicy object. To reproduce the problem boot a DEBUG_PAGEALLOC kernel and run: # mkdir /tmp/x # mount -t tmpfs -o size=100M,mpol=interleave nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=102400k,mpol=interleave:0-3 0 0 # mount -o remount,size=200M nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=204800k,mpol=??? 0 0 # note ? garbage in mpol=... output above # dd if=/dev/zero of=/tmp/x/f count=1 # panic here Panic: BUG: unable to handle kernel NULL pointer dereference at (null) IP: [< (null)>] (null) [...] Oops: 0010 [#1] SMP DEBUG_PAGEALLOC Call Trace: mpol_shared_policy_init+0xa5/0x160 shmem_get_inode+0x209/0x270 shmem_mknod+0x3e/0xf0 shmem_create+0x18/0x20 vfs_create+0xb5/0x130 do_last+0x9a1/0xea0 path_openat+0xb3/0x4d0 do_filp_open+0x42/0xa0 do_sys_open+0xfe/0x1e0 compat_sys_open+0x1b/0x20 cstar_dispatch+0x7/0x1f Non-debug kernels will not crash immediately because referencing the dangling mpol will not cause a fault. Instead the filesystem will reference a freed mempolicy object, which will cause unpredictable behavior. The problem boils down to a dropped mpol reference below if shmem_parse_options() does not allocate a new mpol: config = *sbinfo shmem_parse_options(data, &config, true) mpol_put(sbinfo->mpol) sbinfo->mpol = config.mpol /* BUG: saves unreferenced mpol */ This patch avoids the crash by not releasing the mempolicy if shmem_parse_options() doesn't create a new mpol. How far back does this issue go? I see it in both 2.6.36 and 3.3. I did not look back further. Signed-off-by: Greg Thelen <gthelen@google.com> Acked-by: Hugh Dickins <hughd@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-399
0
10,307
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Document::PopCurrentScript(ScriptElementBase* script) { DCHECK(!current_script_stack_.IsEmpty()); DCHECK_EQ(current_script_stack_.back(), script); current_script_stack_.pop_back(); } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <bokan@chromium.org> Reviewed-by: Stefan Zager <szager@chromium.org> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416
0
10,435
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: SPL_METHOD(SplObjectStorage, setInfo) { spl_SplObjectStorageElement *element; spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *inf; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &inf) == FAILURE) { return; } if (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == FAILURE) { return; } zval_ptr_dtor(&element->inf); element->inf = inf; Z_ADDREF_P(inf); } /* }}} */ /* {{{ proto void SplObjectStorage::next() Commit Message: CWE ID:
0
24,712
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void CL_Disconnect( qboolean showMainMenu ) { if ( !com_cl_running || !com_cl_running->integer ) { return; } Cvar_Set( "r_uiFullScreen", "1" ); if ( clc.demorecording ) { CL_StopRecord_f(); } if ( clc.download ) { FS_FCloseFile( clc.download ); clc.download = 0; } *clc.downloadTempName = *clc.downloadName = 0; Cvar_Set( "cl_downloadName", "" ); #ifdef USE_MUMBLE if (cl_useMumble->integer && mumble_islinked()) { Com_Printf("Mumble: Unlinking from Mumble application\n"); mumble_unlink(); } #endif #ifdef USE_VOIP if (cl_voipSend->integer) { int tmp = cl_voipUseVAD->integer; cl_voipUseVAD->integer = 0; // disable this for a moment. clc.voipOutgoingDataSize = 0; // dump any pending VoIP transmission. Cvar_Set("cl_voipSend", "0"); CL_CaptureVoip(); // clean up any state... cl_voipUseVAD->integer = tmp; } if (clc.voipCodecInitialized) { int i; opus_encoder_destroy(clc.opusEncoder); for (i = 0; i < MAX_CLIENTS; i++) { opus_decoder_destroy(clc.opusDecoder[i]); } clc.voipCodecInitialized = qfalse; } Cmd_RemoveCommand ("voip"); #endif if ( clc.demofile ) { FS_FCloseFile( clc.demofile ); clc.demofile = 0; } if ( uivm && showMainMenu ) { VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE ); } SCR_StopCinematic(); S_ClearSoundBuffer(); if ( clc.state >= CA_CONNECTED ) { CL_AddReliableCommand("disconnect", qtrue); CL_WritePacket(); CL_WritePacket(); CL_WritePacket(); } FS_PureServerSetLoadedPaks("", ""); FS_PureServerSetReferencedPaks( "", "" ); CL_ClearState(); Com_Memset( &clc, 0, sizeof( clc ) ); clc.state = CA_DISCONNECTED; Cvar_Set( "sv_cheats", "1" ); cl_connectedToPureServer = qfalse; #ifdef USE_VOIP clc.voipEnabled = qfalse; #endif if( CL_VideoRecording( ) ) { SCR_UpdateScreen( ); CL_CloseAVI( ); } CL_UpdateGUID( NULL, 0 ); if(!noGameRestart) CL_OldGame(); else noGameRestart = qfalse; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
0
28,934
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void addPaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h) { /*The opposite of the removePaddingBits function olinebits must be >= ilinebits*/ unsigned y; size_t diff = olinebits - ilinebits; size_t obp = 0, ibp = 0; /*bit pointers*/ for(y = 0; y < h; y++) { size_t x; for(x = 0; x < ilinebits; x++) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } /*obp += diff; --> no, fill in some value in the padding bits too, to avoid "Use of uninitialised value of size ###" warning from valgrind*/ for(x = 0; x < diff; x++) setBitOfReversedStream(&obp, out, 0); } } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
0
22,109
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int json_object_equal(json_t *object1, json_t *object2) { const char *key; json_t *value1, *value2; if(json_object_size(object1) != json_object_size(object2)) return 0; json_object_foreach(object1, key, value1) { value2 = json_object_get(object2, key); if(!json_equal(value1, value2)) return 0; } return 1; } 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
0
11,503
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void MockPrinter::SetPrintedPagesCount(int cookie, int number_pages) { EXPECT_EQ(document_cookie_, cookie); EXPECT_EQ(PRINTER_PRINTING, printer_status_); EXPECT_EQ(0, number_pages_); EXPECT_EQ(0, page_number_); number_pages_ = number_pages; page_number_ = 0; pages_.clear(); } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
28,173
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SyncBackendHost::DeactivateDataType( DataTypeController* data_type_controller, ChangeProcessor* change_processor) { base::AutoLock lock(registrar_lock_); registrar_.routing_info.erase(data_type_controller->type()); change_processor->Stop(); std::map<syncable::ModelType, ChangeProcessor*>::size_type erased = processors_.erase(data_type_controller->type()); DCHECK_EQ(erased, 1U); } Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
28,705
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebLocalFrameImpl::PerformMediaPlayerAction( const WebPoint& location, const WebMediaPlayerAction& action) { HitTestResult result = HitTestResultForVisualViewportPos(location); Node* node = result.InnerNode(); if (!IsHTMLVideoElement(*node) && !IsHTMLAudioElement(*node)) return; HTMLMediaElement* media_element = ToHTMLMediaElement(node); switch (action.type) { case WebMediaPlayerAction::kPlay: if (action.enable) media_element->Play(); else media_element->pause(); break; case WebMediaPlayerAction::kMute: media_element->setMuted(action.enable); break; case WebMediaPlayerAction::kLoop: media_element->SetLoop(action.enable); break; case WebMediaPlayerAction::kControls: media_element->SetBooleanAttribute(HTMLNames::controlsAttr, action.enable); break; case WebMediaPlayerAction::kPictureInPicture: DCHECK(media_element->IsHTMLVideoElement()); if (action.enable) { PictureInPictureController::From(node->GetDocument()) .EnterPictureInPicture(ToHTMLVideoElement(media_element), nullptr); } else { PictureInPictureController::From(node->GetDocument()) .ExitPictureInPicture(ToHTMLVideoElement(media_element), nullptr); } break; default: NOTREACHED(); } } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
0
17,260
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static MXFStructuralComponent* mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group) { MXFStructuralComponent *component = NULL; MXFPackage *package = NULL; MXFDescriptor *descriptor = NULL; int i; if (!essence_group || !essence_group->structural_components_count) return NULL; /* essence groups contains multiple representations of the same media, this return the first components with a valid Descriptor typically index 0 */ for (i =0; i < essence_group->structural_components_count; i++){ component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip); if (!component) continue; if (!(package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid))) continue; descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor); if (descriptor) return component; } return NULL; } Commit Message: avformat/mxfdec: Fix av_log context Fixes: out of array access Fixes: mxf-crash-1c2e59bf07a34675bfb3ada5e1ec22fa9f38f923 Found-by: Paul Ch <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-125
0
8,837
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void AutofillPopupViewNativeViews::OnSuggestionsChanged() { CreateChildViews(); DoUpdateBoundsAndRedrawPopup(); } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
0
19,522
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RunLoop::Quit() { if (!origin_task_runner_->RunsTasksInCurrentSequence()) { origin_task_runner_->PostTask( FROM_HERE, base::BindOnce(&RunLoop::Quit, Unretained(this))); return; } quit_called_ = true; if (running_ && delegate_->active_run_loops_.top() == this) { delegate_->Quit(); } } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). R=danakj@chromium.org Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <gab@chromium.org> Reviewed-by: Robert Liao <robliao@chromium.org> Reviewed-by: danakj <danakj@chromium.org> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
0
24,718
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu, struct kvm_interrupt *irq) { if (irq->irq == KVM_INTERRUPT_UNSET) { kvmppc_core_dequeue_external(vcpu); return 0; } kvmppc_core_queue_external(vcpu, irq); kvm_vcpu_kick(vcpu); return 0; } Commit Message: KVM: PPC: Fix oops when checking KVM_CAP_PPC_HTM The following program causes a kernel oops: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kvm.h> main() { int fd = open("/dev/kvm", O_RDWR); ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_PPC_HTM); } This happens because when using the global KVM fd with KVM_CHECK_EXTENSION, kvm_vm_ioctl_check_extension() gets called with a NULL kvm argument, which gets dereferenced in is_kvmppc_hv_enabled(). Spotted while reading the code. Let's use the hv_enabled fallback variable, like everywhere else in this function. Fixes: 23528bb21ee2 ("KVM: PPC: Introduce KVM_CAP_PPC_HTM") Cc: stable@vger.kernel.org # v4.7+ Signed-off-by: Greg Kurz <groug@kaod.org> Reviewed-by: David Gibson <david@gibson.dropbear.id.au> Reviewed-by: Thomas Huth <thuth@redhat.com> Signed-off-by: Paul Mackerras <paulus@ozlabs.org> CWE ID: CWE-476
0
23,529
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SoundChannel::callback(int event, void* user, void *info) { SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1)); channel->process(event, info, (unsigned long)user & 1); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
0
27,393
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct urb *uas_submit_sense_urb(struct scsi_cmnd *cmnd, gfp_t gfp) { struct uas_dev_info *devinfo = cmnd->device->hostdata; struct urb *urb; int err; urb = uas_alloc_sense_urb(devinfo, gfp, cmnd); if (!urb) return NULL; usb_anchor_urb(urb, &devinfo->sense_urbs); err = usb_submit_urb(urb, gfp); if (err) { usb_unanchor_urb(urb); uas_log_cmd_state(cmnd, "sense submit err", err); usb_free_urb(urb); return NULL; } return urb; } Commit Message: USB: uas: fix bug in handling of alternate settings The uas driver has a subtle bug in the way it handles alternate settings. The uas_find_uas_alt_setting() routine returns an altsetting value (the bAlternateSetting number in the descriptor), but uas_use_uas_driver() then treats that value as an index to the intf->altsetting array, which it isn't. Normally this doesn't cause any problems because the various alternate settings have bAlternateSetting values 0, 1, 2, ..., so the value is equal to the index in the array. But this is not guaranteed, and Andrey Konovalov used the syzkaller fuzzer with KASAN to get a slab-out-of-bounds error by violating this assumption. This patch fixes the bug by making uas_find_uas_alt_setting() return a pointer to the altsetting entry rather than either the value or the index. Pointers are less subject to misinterpretation. Signed-off-by: Alan Stern <stern@rowland.harvard.edu> Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.com> CC: Oliver Neukum <oneukum@suse.com> CC: <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-125
0
6,706
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: mld6_print(netdissect_options *ndo, const u_char *bp) { const struct mld6_hdr *mp = (const struct mld6_hdr *)bp; const u_char *ep; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if ((const u_char *)mp + sizeof(*mp) > ep) return; ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay))); ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr))); } Commit Message: CVE-2017-13041/ICMP6: Add more bounds checks. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
0
29,138
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Splash::blitImage(SplashBitmap *src, GBool srcAlpha, int xDest, int yDest, SplashClipResult clipRes) { SplashPipe pipe; SplashColor pixel; Guchar *ap; int w, h, x0, y0, x1, y1, x, y; w = src->getWidth(); h = src->getHeight(); if (clipRes == splashClipAllInside) { x0 = 0; y0 = 0; x1 = w; y1 = h; } else { if (state->clip->getNumPaths()) { x0 = x1 = w; y0 = y1 = h; } else { if ((x0 = splashCeil(state->clip->getXMin()) - xDest) < 0) { x0 = 0; } if ((y0 = splashCeil(state->clip->getYMin()) - yDest) < 0) { y0 = 0; } if ((x1 = splashFloor(state->clip->getXMax()) - xDest) > w) { x1 = w; } if (x1 < x0) { x1 = x0; } if ((y1 = splashFloor(state->clip->getYMax()) - yDest) > h) { y1 = h; } if (y1 < y0) { y1 = y0; } } } if (x0 < w && y0 < h && x0 < x1 && y0 < y1) { pipeInit(&pipe, xDest + x0, yDest + y0, NULL, pixel, (Guchar)splashRound(state->fillAlpha * 255), srcAlpha, gFalse); if (srcAlpha) { for (y = y0; y < y1; ++y) { pipeSetXY(&pipe, xDest + x0, yDest + y); ap = src->getAlphaPtr() + y * w + x0; for (x = x0; x < x1; ++x) { src->getPixel(x, y, pixel); pipe.shape = *ap++; (this->*pipe.run)(&pipe); } } } else { for (y = y0; y < y1; ++y) { pipeSetXY(&pipe, xDest + x0, yDest + y); for (x = x0; x < x1; ++x) { src->getPixel(x, y, pixel); (this->*pipe.run)(&pipe); } } } updateModX(xDest + x0); updateModX(xDest + x1 - 1); updateModY(yDest + y0); updateModY(yDest + y1 - 1); } if (y0 > 0) { blitImageClipped(src, srcAlpha, 0, 0, xDest, yDest, w, y0); } if (y1 < h) { blitImageClipped(src, srcAlpha, 0, y1, xDest, yDest + y1, w, h - y1); } if (x0 > 0 && y0 < y1) { blitImageClipped(src, srcAlpha, 0, y0, xDest, yDest + y0, x0, y1 - y0); } if (x1 < w && y0 < y1) { blitImageClipped(src, srcAlpha, x1, y0, xDest + x1, yDest + y0, w - x1, y1 - y0); } } Commit Message: CWE ID:
0
2,345
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderProcessHostImpl::InitializeChannelProxy() { scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = BrowserThread::GetTaskRunnerForThread(BrowserThread::IO); service_manager::Connector* connector = BrowserContext::GetConnectorFor(browser_context_); if (!connector) { if (!ServiceManagerConnection::GetForProcess()) { ServiceManagerConnection::SetForProcess(ServiceManagerConnection::Create( mojo::MakeRequest(&test_service_), io_task_runner)); } connector = ServiceManagerConnection::GetForProcess()->GetConnector(); } broker_client_invitation_ = std::make_unique<mojo::edk::OutgoingBrokerClientInvitation>(); service_manager::Identity child_identity( mojom::kRendererServiceName, BrowserContext::GetServiceUserIdFor(GetBrowserContext()), base::StringPrintf("%d_%d", id_, instance_id_++)); child_connection_.reset(new ChildConnection(child_identity, broker_client_invitation_.get(), connector, io_task_runner)); mojo::MessagePipe pipe; BindInterface(IPC::mojom::ChannelBootstrap::Name_, std::move(pipe.handle1)); std::unique_ptr<IPC::ChannelFactory> channel_factory = IPC::ChannelMojo::CreateServerFactory( std::move(pipe.handle0), io_task_runner, base::ThreadTaskRunnerHandle::Get()); content::BindInterface(this, &child_control_interface_); ResetChannelProxy(); #if defined(OS_ANDROID) if (GetContentClient()->UsingSynchronousCompositing()) { channel_ = IPC::SyncChannel::Create(this, io_task_runner.get(), base::ThreadTaskRunnerHandle::Get(), &never_signaled_); } #endif // OS_ANDROID if (!channel_) channel_.reset(new IPC::ChannelProxy(this, io_task_runner.get(), base::ThreadTaskRunnerHandle::Get())); channel_->Init(std::move(channel_factory), true /* create_pipe_now */); channel_->GetRemoteAssociatedInterface(&remote_route_provider_); channel_->GetRemoteAssociatedInterface(&renderer_interface_); channel_->Pause(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <weili@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: John Abd-El-Malek <jam@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Sadrul Chowdhury <sadrul@chromium.org> Reviewed-by: Yuzhu Shen <yzshen@chromium.org> Reviewed-by: Robert Sesek <rsesek@chromium.org> Commit-Queue: Ken Rockot <rockot@chromium.org> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
0
21,679
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-119
0
22,027
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool RequiresActionForScriptExecution(const std::string& extension_id, const std::string& host_permissions, Manifest::Location location) { scoped_refptr<const Extension> extension = GetExtensionWithHostPermission(extension_id, host_permissions, location); return extension->permissions_data()->RequiresActionForScriptExecution( extension, -1, // Ignore tab id for these. GURL::EmptyGURL()); } Commit Message: Have the Debugger extension api check that it has access to the tab Check PermissionsData::CanAccessTab() prior to attaching the debugger. BUG=367567 Review URL: https://codereview.chromium.org/352523003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
27,479
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CloseDownClient(ClientPtr client) { Bool really_close_down = client->clientGone || client->closeDownMode == DestroyAll; if (!client->clientGone) { /* ungrab server if grabbing client dies */ if (grabState != GrabNone && grabClient == client) { UngrabServer(client); } BITCLEAR(grabWaiters, client->index); DeleteClientFromAnySelections(client); ReleaseActiveGrabs(client); DeleteClientFontStuff(client); if (!really_close_down) { /* This frees resources that should never be retained * no matter what the close down mode is. Actually we * could do this unconditionally, but it's probably * better not to traverse all the client's resources * twice (once here, once a few lines down in * FreeClientResources) in the common case of * really_close_down == TRUE. */ FreeClientNeverRetainResources(client); client->clientState = ClientStateRetained; if (ClientStateCallback) { NewClientInfoRec clientinfo; clientinfo.client = client; clientinfo.prefix = (xConnSetupPrefix *) NULL; clientinfo.setup = (xConnSetup *) NULL; CallCallbacks((&ClientStateCallback), (void *) &clientinfo); } } client->clientGone = TRUE; /* so events aren't sent to client */ if (ClientIsAsleep(client)) ClientSignal(client); ProcessWorkQueueZombies(); CloseDownConnection(client); output_pending_clear(client); mark_client_not_ready(client); /* If the client made it to the Running stage, nClients has * been incremented on its behalf, so we need to decrement it * now. If it hasn't gotten to Running, nClients has *not* * been incremented, so *don't* decrement it. */ if (client->clientState != ClientStateInitial) { --nClients; } } if (really_close_down) { if (client->clientState == ClientStateRunning && nClients == 0) dispatchException |= dispatchExceptionAtReset; client->clientState = ClientStateGone; if (ClientStateCallback) { NewClientInfoRec clientinfo; clientinfo.client = client; clientinfo.prefix = (xConnSetupPrefix *) NULL; clientinfo.setup = (xConnSetup *) NULL; CallCallbacks((&ClientStateCallback), (void *) &clientinfo); } TouchListenerGone(client->clientAsMask); FreeClientResources(client); /* Disable client ID tracking. This must be done after * ClientStateCallback. */ ReleaseClientIds(client); #ifdef XSERVER_DTRACE XSERVER_CLIENT_DISCONNECT(client->index); #endif if (client->index < nextFreeClientID) nextFreeClientID = client->index; clients[client->index] = NullClient; SmartLastClient = NullClient; dixFreeObjectWithPrivates(client, PRIVATE_CLIENT); while (!clients[currentMaxClients - 1]) currentMaxClients--; } } Commit Message: CWE ID: CWE-20
0
28,261
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool DebuggerDetachFunction::RunAsync() { std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitClientHost()) return false; client_host_->Close(); SendResponse(true); return true; } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. TBR=alexclarke@chromium.org Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
1
19,474
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: fbFetch_c4 (const FbBits *bits, int x, int width, CARD32 *buffer, miIndexedPtr indexed) { int i; for (i = 0; i < width; ++i) { CARD32 p = Fetch4(bits, i + x); WRITE(buffer++, indexed->rgba[p]); } } Commit Message: CWE ID: CWE-189
0
9,080
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { unsigned long rlim = rlimit(RLIMIT_DATA); struct mm_struct *mm = current->mm; struct vm_area_struct *vma; int error; if (arg5 || (arg4 && opt != PR_SET_MM_AUXV)) return -EINVAL; if (!capable(CAP_SYS_RESOURCE)) return -EPERM; if (opt == PR_SET_MM_EXE_FILE) return prctl_set_mm_exe_file(mm, (unsigned int)addr); if (addr >= TASK_SIZE || addr < mmap_min_addr) return -EINVAL; error = -EINVAL; down_read(&mm->mmap_sem); vma = find_vma(mm, addr); switch (opt) { case PR_SET_MM_START_CODE: mm->start_code = addr; break; case PR_SET_MM_END_CODE: mm->end_code = addr; break; case PR_SET_MM_START_DATA: mm->start_data = addr; break; case PR_SET_MM_END_DATA: mm->end_data = addr; break; case PR_SET_MM_START_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (mm->brk - addr) + (mm->end_data - mm->start_data) > rlim) goto out; mm->start_brk = addr; break; case PR_SET_MM_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (addr - mm->start_brk) + (mm->end_data - mm->start_data) > rlim) goto out; mm->brk = addr; break; /* * If command line arguments and environment * are placed somewhere else on stack, we can * set them up here, ARG_START/END to setup * command line argumets and ENV_START/END * for environment. */ case PR_SET_MM_START_STACK: case PR_SET_MM_ARG_START: case PR_SET_MM_ARG_END: case PR_SET_MM_ENV_START: case PR_SET_MM_ENV_END: if (!vma) { error = -EFAULT; goto out; } if (opt == PR_SET_MM_START_STACK) mm->start_stack = addr; else if (opt == PR_SET_MM_ARG_START) mm->arg_start = addr; else if (opt == PR_SET_MM_ARG_END) mm->arg_end = addr; else if (opt == PR_SET_MM_ENV_START) mm->env_start = addr; else if (opt == PR_SET_MM_ENV_END) mm->env_end = addr; break; /* * This doesn't move auxiliary vector itself * since it's pinned to mm_struct, but allow * to fill vector with new values. It's up * to a caller to provide sane values here * otherwise user space tools which use this * vector might be unhappy. */ case PR_SET_MM_AUXV: { unsigned long user_auxv[AT_VECTOR_SIZE]; if (arg4 > sizeof(user_auxv)) goto out; up_read(&mm->mmap_sem); if (copy_from_user(user_auxv, (const void __user *)addr, arg4)) return -EFAULT; /* Make sure the last entry is always AT_NULL */ user_auxv[AT_VECTOR_SIZE - 2] = 0; user_auxv[AT_VECTOR_SIZE - 1] = 0; BUILD_BUG_ON(sizeof(user_auxv) != sizeof(mm->saved_auxv)); task_lock(current); memcpy(mm->saved_auxv, user_auxv, arg4); task_unlock(current); return 0; } default: goto out; } error = 0; out: up_read(&mm->mmap_sem); return error; } Commit Message: kernel/sys.c: fix stack memory content leak via UNAME26 Calling uname() with the UNAME26 personality set allows a leak of kernel stack contents. This fixes it by defensively calculating the length of copy_to_user() call, making the len argument unsigned, and initializing the stack buffer to zero (now technically unneeded, but hey, overkill). CVE-2012-0957 Reported-by: PaX Team <pageexec@freemail.hu> Signed-off-by: Kees Cook <keescook@chromium.org> Cc: Andi Kleen <ak@linux.intel.com> Cc: PaX Team <pageexec@freemail.hu> Cc: Brad Spengler <spender@grsecurity.net> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-16
0
749
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void init_once(void *foo) { struct btrfs_inode *ei = (struct btrfs_inode *) foo; inode_init_once(&ei->vfs_inode); } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <chris.mason@fusionio.com> Reported-by: Pascal Junod <pascal@junod.info> CWE ID: CWE-310
0
9,976
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int ext4_clear_blocks(handle_t *handle, struct inode *inode, struct buffer_head *bh, ext4_fsblk_t block_to_free, unsigned long count, __le32 *first, __le32 *last) { __le32 *p; int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED; if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) flags |= EXT4_FREE_BLOCKS_METADATA; if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free, count)) { ext4_error(inode->i_sb, "inode #%lu: " "attempt to clear blocks %llu len %lu, invalid", inode->i_ino, (unsigned long long) block_to_free, count); return 1; } if (try_to_extend_transaction(handle, inode)) { if (bh) { BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); ext4_handle_dirty_metadata(handle, inode, bh); } ext4_mark_inode_dirty(handle, inode); ext4_truncate_restart_trans(handle, inode, blocks_for_truncate(inode)); if (bh) { BUFFER_TRACE(bh, "retaking write access"); ext4_journal_get_write_access(handle, bh); } } for (p = first; p < last; p++) *p = 0; ext4_free_blocks(handle, inode, 0, block_to_free, count, flags); return 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
0
10,942
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebGLRenderingContextBase::LoseContextImpl( WebGLRenderingContextBase::LostContextMode mode, AutoRecoveryMethod auto_recovery_method) { if (isContextLost()) return; context_lost_mode_ = mode; DCHECK_NE(context_lost_mode_, kNotLostContext); auto_recovery_method_ = auto_recovery_method; for (size_t i = 0; i < extensions_.size(); ++i) { ExtensionTracker* tracker = extensions_[i]; tracker->LoseExtension(false); } for (size_t i = 0; i < kWebGLExtensionNameCount; ++i) extension_enabled_[i] = false; RemoveAllCompressedTextureFormats(); if (mode != kRealLostContext) DestroyContext(); ConsoleDisplayPreference display = (mode == kRealLostContext) ? kDisplayInConsole : kDontDisplayInConsole; SynthesizeGLError(GC3D_CONTEXT_LOST_WEBGL, "loseContext", "context lost", display); restore_allowed_ = false; DeactivateContext(this); if (auto_recovery_method_ == kWhenAvailable) AddToEvictedList(this); dispatch_context_lost_event_timer_.StartOneShot(TimeDelta(), FROM_HERE); } Commit Message: Simplify WebGL error message The WebGL exception message text contains the full URL of a blocked cross-origin resource. It should instead contain only a generic notice. Bug: 799847 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I3a7f00462a4643c41882f2ee7e7767e6d631557e Reviewed-on: https://chromium-review.googlesource.com/854986 Reviewed-by: Brandon Jones <bajones@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Eric Lawrence <elawrence@chromium.org> Cr-Commit-Position: refs/heads/master@{#528458} CWE ID: CWE-20
0
27,939
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void NaClIPCAdapter::ClearToBeSent() { lock_.AssertAcquired(); std::string empty; locked_data_.to_be_sent_.swap(empty); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
9,420
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: uint64_t getCurrentTimeInMs() { return myCurrentTime; } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
0
26,492
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void __inet6_csk_dst_store(struct sock *sk, struct dst_entry *dst, const struct in6_addr *daddr, const struct in6_addr *saddr) { __ip6_dst_store(sk, dst, daddr, saddr); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
0
9,655
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: const SecurityOrigin* Document::topOrigin() const { return topDocument()->securityOrigin(); } Commit Message: Unreviewed, rolling out r147402. http://trac.webkit.org/changeset/147402 https://bugs.webkit.org/show_bug.cgi?id=112903 Source/WebCore: * dom/Document.cpp: (WebCore::Document::processHttpEquiv): * loader/DocumentLoader.cpp: (WebCore::DocumentLoader::responseReceived): LayoutTests: * http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html: * http/tests/security/XFrameOptions/x-frame-options-deny.html: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
17,092
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool TabSpecificContentSettings::IsBlockageIndicated( ContentSettingsType content_type) const { return content_blockage_indicated_to_user_[content_type]; } Commit Message: Check the content setting type is valid. BUG=169770 Review URL: https://codereview.chromium.org/11875013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176687 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
4,771
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type) { struct net_device *dev; ASSERT_RTNL(); for_each_netdev(net, dev) if (dev->type == type) return dev; return NULL; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <martin.ferrari@gmail.com> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
0
19,001
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void netdev_wait_allrefs(struct net_device *dev) { unsigned long rebroadcast_time, warning_time; linkwatch_forget_dev(dev); rebroadcast_time = warning_time = jiffies; while (atomic_read(&dev->refcnt) != 0) { if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { rtnl_lock(); /* Rebroadcast unregister notification */ call_netdevice_notifiers(NETDEV_UNREGISTER, dev); /* don't resend NETDEV_UNREGISTER_BATCH, _BATCH users * should have already handle it the first time */ if (test_bit(__LINK_STATE_LINKWATCH_PENDING, &dev->state)) { /* We must not have linkwatch events * pending on unregister. If this * happens, we simply run the queue * unscheduled, resulting in a noop * for this device. */ linkwatch_run_queue(); } __rtnl_unlock(); rebroadcast_time = jiffies; } msleep(250); if (time_after(jiffies, warning_time + 10 * HZ)) { printk(KERN_EMERG "unregister_netdevice: " "waiting for %s to become free. Usage " "count = %d\n", dev->name, atomic_read(&dev->refcnt)); warning_time = jiffies; } } } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <martin.ferrari@gmail.com> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
0
1,737
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
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
1
9,736
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL("about:swappedout")) return WebKit::WebNavigationPolicyIgnore; return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { if (request.httpMethod() == "GET") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
1
27,295
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info) { bool pr = false; u32 msr = msr_info->index; u64 data = msr_info->data; switch (msr) { case MSR_AMD64_NB_CFG: case MSR_IA32_UCODE_REV: case MSR_IA32_UCODE_WRITE: case MSR_VM_HSAVE_PA: case MSR_AMD64_PATCH_LOADER: case MSR_AMD64_BU_CFG2: break; case MSR_EFER: return set_efer(vcpu, data); case MSR_K7_HWCR: data &= ~(u64)0x40; /* ignore flush filter disable */ data &= ~(u64)0x100; /* ignore ignne emulation enable */ data &= ~(u64)0x8; /* ignore TLB cache disable */ data &= ~(u64)0x40000; /* ignore Mc status write enable */ if (data != 0) { vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n", data); return 1; } break; case MSR_FAM10H_MMIO_CONF_BASE: if (data != 0) { vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: " "0x%llx\n", data); return 1; } break; case MSR_IA32_DEBUGCTLMSR: if (!data) { /* We support the non-activated case already */ break; } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) { /* Values other than LBR and BTF are vendor-specific, thus reserved and should throw a #GP */ return 1; } vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n", __func__, data); break; case 0x200 ... 0x2ff: return kvm_mtrr_set_msr(vcpu, msr, data); case MSR_IA32_APICBASE: return kvm_set_apic_base(vcpu, msr_info); case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff: return kvm_x2apic_msr_write(vcpu, msr, data); case MSR_IA32_TSCDEADLINE: kvm_set_lapic_tscdeadline_msr(vcpu, data); break; case MSR_IA32_TSC_ADJUST: if (guest_cpuid_has_tsc_adjust(vcpu)) { if (!msr_info->host_initiated) { s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr; adjust_tsc_offset_guest(vcpu, adj); } vcpu->arch.ia32_tsc_adjust_msr = data; } break; case MSR_IA32_MISC_ENABLE: vcpu->arch.ia32_misc_enable_msr = data; break; case MSR_IA32_SMBASE: if (!msr_info->host_initiated) return 1; vcpu->arch.smbase = data; break; case MSR_KVM_WALL_CLOCK_NEW: case MSR_KVM_WALL_CLOCK: vcpu->kvm->arch.wall_clock = data; kvm_write_wall_clock(vcpu->kvm, data); break; case MSR_KVM_SYSTEM_TIME_NEW: case MSR_KVM_SYSTEM_TIME: { u64 gpa_offset; struct kvm_arch *ka = &vcpu->kvm->arch; kvmclock_reset(vcpu); if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) { bool tmp = (msr == MSR_KVM_SYSTEM_TIME); if (ka->boot_vcpu_runs_old_kvmclock != tmp) set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests); ka->boot_vcpu_runs_old_kvmclock = tmp; } vcpu->arch.time = data; kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu); /* we verify if the enable bit is set... */ if (!(data & 1)) break; gpa_offset = data & ~(PAGE_MASK | 1); if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_time, data & ~1ULL, sizeof(struct pvclock_vcpu_time_info))) vcpu->arch.pv_time_enabled = false; else vcpu->arch.pv_time_enabled = true; break; } case MSR_KVM_ASYNC_PF_EN: if (kvm_pv_enable_async_pf(vcpu, data)) return 1; break; case MSR_KVM_STEAL_TIME: if (unlikely(!sched_info_on())) return 1; if (data & KVM_STEAL_RESERVED_MASK) return 1; if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime, data & KVM_STEAL_VALID_BITS, sizeof(struct kvm_steal_time))) return 1; vcpu->arch.st.msr_val = data; if (!(data & KVM_MSR_ENABLED)) break; kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu); break; case MSR_KVM_PV_EOI_EN: if (kvm_lapic_enable_pv_eoi(vcpu, data)) return 1; break; case MSR_IA32_MCG_CTL: case MSR_IA32_MCG_STATUS: case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1: return set_msr_mce(vcpu, msr, data); case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3: case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1: pr = true; /* fall through */ case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3: case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1: if (kvm_pmu_is_valid_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr_info); if (pr || data != 0) vcpu_unimpl(vcpu, "disabled perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; case MSR_K7_CLK_CTL: /* * Ignore all writes to this no longer documented MSR. * Writes are only relevant for old K7 processors, * all pre-dating SVM, but a recommended workaround from * AMD for these chips. It is possible to specify the * affected processor models on the command line, hence * the need to ignore the workaround. */ break; case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15: case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4: case HV_X64_MSR_CRASH_CTL: return kvm_hv_set_msr_common(vcpu, msr, data, msr_info->host_initiated); case MSR_IA32_BBL_CR_CTL3: /* Drop writes to this legacy MSR -- see rdmsr * counterpart for further detail. */ vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; case MSR_AMD64_OSVW_ID_LENGTH: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.length = data; break; case MSR_AMD64_OSVW_STATUS: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.status = data; break; default: if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr)) return xen_hvm_config(vcpu, data); if (kvm_pmu_is_valid_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr_info); if (!ignore_msrs) { vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data); return 1; } else { vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; } } return 0; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID:
0
29,531
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void perf_remove_from_owner(struct perf_event *event) { struct task_struct *owner; rcu_read_lock(); /* * Matches the smp_store_release() in perf_event_exit_task(). If we * observe !owner it means the list deletion is complete and we can * indeed free this event, otherwise we need to serialize on * owner->perf_event_mutex. */ owner = lockless_dereference(event->owner); if (owner) { /* * Since delayed_put_task_struct() also drops the last * task reference we can safely take a new reference * while holding the rcu_read_lock(). */ get_task_struct(owner); } rcu_read_unlock(); if (owner) { /* * If we're here through perf_event_exit_task() we're already * holding ctx->mutex which would be an inversion wrt. the * normal lock order. * * However we can safely take this lock because its the child * ctx->mutex. */ mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); /* * We have to re-check the event->owner field, if it is cleared * we raced with perf_event_exit_task(), acquiring the mutex * ensured they're done, and we can proceed with freeing the * event. */ if (event->owner) { list_del_init(&event->owner_entry); smp_store_release(&event->owner, NULL); } mutex_unlock(&owner->perf_event_mutex); put_task_struct(owner); } } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <joaodias@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Arnaldo Carvalho de Melo <acme@redhat.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Kees Cook <keescook@chromium.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Min Chong <mchong@google.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Stephane Eranian <eranian@google.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Vince Weaver <vincent.weaver@maine.edu> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/20170106131444.GZ3174@twins.programming.kicks-ass.net Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-362
0
26,138
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: context_length_arg (char const *str, int *out) { uintmax_t value; if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK && 0 <= (*out = value) && *out == value)) { error (EXIT_TROUBLE, 0, "%s: %s", str, _("invalid context length argument")); } page size, unless a read yields a partial page. */ static char *buffer; /* Base of buffer. */ static size_t bufalloc; /* Allocated buffer size, counting slop. */ #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */ static int bufdesc; /* File descriptor. */ static char *bufbeg; /* Beginning of user-visible stuff. */ static char *buflim; /* Limit of user-visible stuff. */ static size_t pagesize; /* alignment of memory pages */ static off_t bufoffset; /* Read offset; defined on regular files. */ static off_t after_last_match; /* Pointer after last matching line that would have been output if we were outputting characters. */ /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be an integer or a pointer. Both args must be free of side effects. */ #define ALIGN_TO(val, alignment) \ ((size_t) (val) % (alignment) == 0 \ ? (val) \ : (val) + ((alignment) - (size_t) (val) % (alignment))) /* Reset the buffer for a new file, returning zero if we should skip it. Initialize on the first time through. */ static int reset (int fd, char const *file, struct stats *stats) { if (! pagesize) { pagesize = getpagesize (); if (pagesize == 0 || 2 * pagesize + 1 <= pagesize) abort (); bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1; buffer = xmalloc (bufalloc); } bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize); bufbeg[-1] = eolbyte; bufdesc = fd; if (S_ISREG (stats->stat.st_mode)) { if (file) bufoffset = 0; else { bufoffset = lseek (fd, 0, SEEK_CUR); if (bufoffset < 0) { suppressible_error (_("lseek failed"), errno); return 0; } } } return 1; } /* Read new stuff into the buffer, saving the specified amount of old stuff. When we're done, 'bufbeg' points to the beginning of the buffer contents, and 'buflim' points just after the end. Return zero if there's an error. */ static int fillbuf (size_t save, struct stats const *stats) { size_t fillsize = 0; int cc = 1; char *readbuf; size_t readsize; /* Offset from start of buffer to start of old stuff that we want to save. */ size_t saved_offset = buflim - save - buffer; if (pagesize <= buffer + bufalloc - buflim) { readbuf = buflim; bufbeg = buflim - save; } else { size_t minsize = save + pagesize; size_t newsize; size_t newalloc; char *newbuf; /* Grow newsize until it is at least as great as minsize. */ for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2) if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2) xalloc_die (); /* Try not to allocate more memory than the file size indicates, as that might cause unnecessary memory exhaustion if the file is large. However, do not use the original file size as a heuristic if we've already read past the file end, as most likely the file is growing. */ if (S_ISREG (stats->stat.st_mode)) { off_t to_be_read = stats->stat.st_size - bufoffset; off_t maxsize_off = save + to_be_read; if (0 <= to_be_read && to_be_read <= maxsize_off && maxsize_off == (size_t) maxsize_off && minsize <= (size_t) maxsize_off && (size_t) maxsize_off < newsize) newsize = maxsize_off; } /* Add enough room so that the buffer is aligned and has room for byte sentinels fore and aft. */ newalloc = newsize + pagesize + 1; newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer; readbuf = ALIGN_TO (newbuf + 1 + save, pagesize); bufbeg = readbuf - save; memmove (bufbeg, buffer + saved_offset, save); bufbeg[-1] = eolbyte; if (newbuf != buffer) { free (buffer); buffer = newbuf; } } readsize = buffer + bufalloc - readbuf; readsize -= readsize % pagesize; if (! fillsize) { ssize_t bytesread; while ((bytesread = read (bufdesc, readbuf, readsize)) < 0 && errno == EINTR) continue; if (bytesread < 0) cc = 0; else fillsize = bytesread; } bufoffset += fillsize; #if defined HAVE_DOS_FILE_CONTENTS if (fillsize) fillsize = undossify_input (readbuf, fillsize); #endif buflim = readbuf + fillsize; return cc; } /* Flags controlling the style of output. */ static enum { BINARY_BINARY_FILES, TEXT_BINARY_FILES, WITHOUT_MATCH_BINARY_FILES } binary_files; /* How to handle binary files. */ static int filename_mask; /* If zero, output nulls after filenames. */ static int out_quiet; /* Suppress all normal output. */ static int out_invert; /* Print nonmatching stuff. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int count_matches; /* Count matching lines. */ static int list_files; /* List matching files. */ static int no_filenames; /* Suppress file names. */ static off_t max_count; /* Stop after outputting this many lines from an input file. */ static int line_buffered; /* If nonzero, use line buffering, i.e. fflush everyline out. */ static char const *lastnl; /* Pointer after last newline counted. */ static char const *lastout; /* Pointer after last character output; NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. Always kept 0 if out_quiet is true. */ static int done_on_match; /* Stop scanning file on first match. */ static int exit_on_match; /* Exit on first match. */ /* Add two numbers that count input bytes or lines, and report an error if the addition overflows. */ static uintmax_t add_count (uintmax_t a, uintmax_t b) { uintmax_t sum = a + b; if (sum < a) error (EXIT_TROUBLE, 0, _("input is too large to count")); return sum; } static void nlscan (char const *lim) { size_t newlines = 0; char const *beg; for (beg = lastnl; beg < lim; beg++) { beg = memchr (beg, eolbyte, lim - beg); if (!beg) break; newlines++; } totalnl = add_count (totalnl, newlines); lastnl = lim; } /* Print the current filename. */ static void print_filename (void) { pr_sgr_start_if (filename_color); fputs (filename, stdout); pr_sgr_end_if (filename_color); } /* Print a character separator. */ static void print_sep (char sep) { pr_sgr_start_if (sep_color); fputc (sep, stdout); pr_sgr_end_if (sep_color); } /* Print a line number or a byte offset. */ static void print_offset (uintmax_t pos, int min_width, const char *color) { /* Do not rely on printf to print pos, since uintmax_t may be longer than long, and long long is not portable. */ char buf[sizeof pos * CHAR_BIT]; char *p = buf + sizeof buf; do { *--p = '0' + pos % 10; --min_width; } while ((pos /= 10) != 0); /* Do this to maximize the probability of alignment across lines. */ if (align_tabs) while (--min_width >= 0) *--p = ' '; pr_sgr_start_if (color); fwrite (p, 1, buf + sizeof buf - p, stdout); pr_sgr_end_if (color); } /* Print a whole line head (filename, line, byte). */ static void print_line_head (char const *beg, char const *lim, int sep) { int pending_sep = 0; if (out_file) { print_filename (); if (filename_mask) pending_sep = 1; else fputc (0, stdout); } if (out_line) { if (lastnl < lim) { nlscan (beg); totalnl = add_count (totalnl, 1); lastnl = lim; } if (pending_sep) print_sep (sep); print_offset (totalnl, 4, line_num_color); pending_sep = 1; } if (out_byte) { uintmax_t pos = add_count (totalcc, beg - bufbeg); #if defined HAVE_DOS_FILE_CONTENTS pos = dossified_pos (pos); #endif if (pending_sep) print_sep (sep); print_offset (pos, 6, byte_num_color); pending_sep = 1; } if (pending_sep) { /* This assumes sep is one column wide. Try doing this any other way with Unicode (and its combining and wide characters) filenames and you're wasting your efforts. */ if (align_tabs) fputs ("\t\b", stdout); print_sep (sep); } } static const char * print_line_middle (const char *beg, const char *lim, const char *line_color, const char *match_color) { size_t match_size; size_t match_offset; const char *cur = beg; const char *mid = NULL; while (cur < lim && ((match_offset = execute (beg, lim - beg, &match_size, beg + (cur - beg))) != (size_t) -1)) { char const *b = beg + match_offset; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; /* Avoid hanging on grep --color "" foo */ if (match_size == 0) { /* Make minimal progress; there may be further non-empty matches. */ /* XXX - Could really advance by one whole multi-octet character. */ match_size = 1; if (!mid) mid = cur; } else { /* This function is called on a matching line only, but is it selected or rejected/context? */ if (only_matching) print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED : SEP_CHAR_SELECTED)); else { pr_sgr_start (line_color); if (mid) { cur = mid; mid = NULL; } fwrite (cur, sizeof (char), b - cur, stdout); } pr_sgr_start_if (match_color); fwrite (b, sizeof (char), match_size, stdout); pr_sgr_end_if (match_color); if (only_matching) fputs ("\n", stdout); } cur = b + match_size; } if (only_matching) cur = lim; else if (mid) cur = mid; return cur; } static const char * print_line_tail (const char *beg, const char *lim, const char *line_color) { size_t eol_size; size_t tail_size; eol_size = (lim > beg && lim[-1] == eolbyte); eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r'); tail_size = lim - eol_size - beg; if (tail_size > 0) { pr_sgr_start (line_color); fwrite (beg, 1, tail_size, stdout); beg += tail_size; pr_sgr_end (line_color); } return beg; } static void prline (char const *beg, char const *lim, int sep) { int matching; const char *line_color; const char *match_color; if (!only_matching) print_line_head (beg, lim, sep); matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert; if (color_option) { line_color = (((sep == SEP_CHAR_SELECTED) ^ (out_invert && (color_option < 0))) ? selected_line_color : context_line_color); match_color = (sep == SEP_CHAR_SELECTED ? selected_match_color : context_match_color); } else line_color = match_color = NULL; /* Shouldn't be used. */ if ((only_matching && matching) || (color_option && (*line_color || *match_color))) { /* We already know that non-matching lines have no match (to colorize). */ if (matching && (only_matching || *match_color)) beg = print_line_middle (beg, lim, line_color, match_color); /* FIXME: this test may be removable. */ if (!only_matching && *line_color) beg = print_line_tail (beg, lim, line_color); } if (!only_matching && lim > beg) fwrite (beg, 1, lim - beg, stdout); if (ferror (stdout)) { write_error_seen = 1; error (EXIT_TROUBLE, 0, _("write error")); } lastout = lim; if (line_buffered) fflush (stdout); } /* Print pending lines of trailing context prior to LIM. Trailing context ends at the next matching line when OUTLEFT is 0. */ static void prpending (char const *lim) { if (!lastout) lastout = bufbeg; while (pending > 0 && lastout < lim) { char const *nl = memchr (lastout, eolbyte, lim - lastout); size_t match_size; --pending; if (outleft || ((execute (lastout, nl + 1 - lastout, &match_size, NULL) == (size_t) -1) == !out_invert)) prline (lastout, nl + 1, SEP_CHAR_REJECTED); else pending = 0; } } /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { static int used; /* avoid printing SEP_STR_GROUP before any output */ char const *bp, *p; char eol = eolbyte; int i, n; if (!out_quiet && pending > 0) prpending (beg); /* Deal with leading context crap. */ bp = lastout ? lastout : bufbeg; for (i = 0; i < out_before; ++i) if (p > bp) do --p; while (p[-1] != eol); /* We print the SEP_STR_GROUP separator only if our output is discontiguous from the last output in the file. */ if ((out_before || out_after) && used && p != lastout && group_separator) { pr_sgr_start_if (sep_color); fputs (group_separator, stdout); pr_sgr_end_if (sep_color); fputc ('\n', stdout); } while (p < beg) { char const *nl = memchr (p, eol, beg - p); nl++; prline (p, nl, SEP_CHAR_REJECTED); p = nl; } } if (nlinesp) { /* Caller wants a line count. */ for (n = 0; p < lim && n < outleft; n++) { char const *nl = memchr (p, eol, lim - p); nl++; if (!out_quiet) prline (p, nl, SEP_CHAR_SELECTED); p = nl; } *nlinesp = n; /* relying on it that this function is never called when outleft = 0. */ after_last_match = bufoffset - (buflim - p); } else if (!out_quiet) prline (beg, lim, SEP_CHAR_SELECTED); pending = out_quiet ? 0 : out_after; used = 1; } static size_t do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr) { size_t result; const char *line_next; /* With the current implementation, using --ignore-case with a multi-byte character set is very inefficient when applied to a large buffer containing many matches. We can avoid much of the wasted effort by matching line-by-line. FIXME: this is just an ugly workaround, and it doesn't really belong here. Also, PCRE is always using this same per-line matching algorithm. Either we fix -i, or we should refactor this code---for example, we could add another function pointer to struct matcher to split the buffer passed to execute. It would perform the memchr if line-by-line matching is necessary, or just return buf + size otherwise. */ if (MB_CUR_MAX == 1 || !match_icase) return execute (buf, size, match_size, start_ptr); for (line_next = buf; line_next < buf + size; ) { const char *line_buf = line_next; const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf); if (line_end == NULL) line_next = line_end = buf + size; else line_next = line_end + 1; if (start_ptr && start_ptr >= line_end) continue; result = execute (line_buf, line_next - line_buf, match_size, start_ptr); if (result != (size_t) -1) return (line_buf - buf) + result; } return (size_t) -1; } /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) { int nlines, n; char const *p; size_t match_offset; size_t match_size; { char const *b = p + match_offset; char const *endp = b + match_size; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; outleft--; if (!outleft || done_on_match) } } else if (p < b) { prtext (p, b, &n); nlines += n; outleft -= n; if (!outleft) return nlines; } p = endp; } if (out_invert && p < lim) { prtext (p, lim, &n); nlines += n; outleft -= n; } return nlines; } /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) { int nlines, i; int not_text; size_t residue, save; char oldc; return 0; if (file && directories == RECURSE_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) { /* Close fd now, so that we don't open a lot of file descriptors when we recurse deeply. */ if (close (fd) != 0) suppressible_error (file, errno); return grepdir (file, stats) - 2; } totalcc = 0; lastout = 0; totalnl = 0; outleft = max_count; after_last_match = 0; pending = 0; nlines = 0; residue = 0; save = 0; if (! fillbuf (save, stats)) { suppressible_error (filename, errno); return 0; } not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet) || binary_files == WITHOUT_MATCH_BINARY_FILES) && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg)); if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES) return 0; done_on_match += not_text; out_quiet += not_text; for (;;) { lastnl = bufbeg; if (lastout) lastout = bufbeg; beg = bufbeg + save; /* no more data to scan (eof) except for maybe a residue -> break */ if (beg == buflim) break; /* Determine new residue (the length of an incomplete line at the end of the buffer, 0 means there is no incomplete last line). */ oldc = beg[-1]; beg[-1] = eol; for (lim = buflim; lim[-1] != eol; lim--) continue; beg[-1] = oldc; if (lim == beg) lim = beg - residue; beg -= residue; residue = buflim - lim; if (beg < lim) { if (outleft) nlines += grepbuf (beg, lim); if (pending) prpending (lim); if ((!outleft && !pending) || (nlines && done_on_match && !out_invert)) goto finish_grep; } /* The last OUT_BEFORE lines at the end of the buffer will be needed as leading context if there is a matching line at the begin of the next data. Make beg point to their begin. */ i = 0; beg = lim; while (i < out_before && beg > bufbeg && beg != lastout) { ++i; do --beg; while (beg[-1] != eol); } /* detect if leading context is discontinuous from last printed line. */ if (beg != lastout) lastout = 0; /* Handle some details and read more data to scan. */ save = residue + lim - beg; if (out_byte) totalcc = add_count (totalcc, buflim - bufbeg - save); if (out_line) nlscan (beg); if (! fillbuf (save, stats)) { suppressible_error (filename, errno); goto finish_grep; } } if (residue) { *buflim++ = eol; if (outleft) nlines += grepbuf (bufbeg + save - residue, buflim); if (pending) prpending (buflim); } finish_grep: done_on_match -= not_text; out_quiet -= not_text; if ((not_text & ~out_quiet) && nlines != 0) printf (_("Binary file %s matches\n"), filename); return nlines; } static int grepfile (char const *file, struct stats *stats) { int desc; int count; int status; grepfile (char const *file, struct stats *stats) { int desc; int count; int status; filename = (file ? file : label ? label : _("(standard input)")); /* Don't open yet, since that might have side effects on a device. */ desc = -1; } else { /* When skipping directories, don't worry about directories that can't be opened. */ desc = open (file, O_RDONLY); if (desc < 0 && directories != SKIP_DIRECTORIES) { suppressible_error (file, errno); return 1; } } if (desc < 0 ? stat (file, &stats->stat) != 0 : fstat (desc, &stats->stat) != 0) { suppressible_error (filename, errno); if (file) close (desc); return 1; } if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) || (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode) || S_ISBLK (stats->stat.st_mode) || S_ISSOCK (stats->stat.st_mode) || S_ISFIFO (stats->stat.st_mode)))) { if (file) close (desc); return 1; } /* If there is a regular file on stdout and the current file refers to the same i-node, we have to report the problem and skip it. Otherwise when matching lines from some other input reach the disk before we open this file, we can end up reading and matching those lines and appending them to the file from which we're reading. Then we'd have what appears to be an infinite loop that'd terminate only upon filling the output file system or reaching a quota. However, there is no risk of an infinite loop if grep is generating no output, i.e., with --silent, --quiet, -q. Similarly, with any of these: --max-count=N (-m) (for N >= 2) --files-with-matches (-l) --files-without-match (-L) there is no risk of trouble. For --max-count=1, grep stops after printing the first match, so there is no risk of malfunction. But even --max-count=2, with input==output, while there is no risk of infloop, there is a race condition that could result in "alternate" output. */ if (!out_quiet && list_files == 0 && 1 < max_count && S_ISREG (out_stat.st_mode) && out_stat.st_ino && SAME_INODE (stats->stat, out_stat)) { if (! suppress_errors) error (0, 0, _("input file %s is also the output"), quote (filename)); errseen = 1; if (file) close (desc); return 1; } if (desc < 0) { desc = open (file, O_RDONLY); if (desc < 0) { suppressible_error (file, errno); return 1; } } #if defined SET_BINARY /* Set input to binary mode. Pipes are simulated with files on DOS, so this includes the case of "foo | grep bar". */ if (!isatty (desc)) SET_BINARY (desc); #endif count = grep (desc, file, stats); if (count < 0) status = count + 2; else { if (count_matches) { if (out_file) { print_filename (); if (filename_mask) print_sep (SEP_CHAR_SELECTED); else fputc (0, stdout); } printf ("%d\n", count); } else fputc (0, stdout); } printf ("%d\n", count); } status = !count; if (! file) { off_t required_offset = outleft ? bufoffset : after_last_match; if (required_offset != bufoffset && lseek (desc, required_offset, SEEK_SET) < 0 && S_ISREG (stats->stat.st_mode)) suppressible_error (filename, errno); } else while (close (desc) != 0) if (errno != EINTR) { suppressible_error (file, errno); break; } } Commit Message: CWE ID: CWE-189
1
9,585
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int validate_core_offset(const struct kvm_one_reg *reg) { u64 off = core_reg_offset_from_id(reg->id); int size; switch (off) { case KVM_REG_ARM_CORE_REG(regs.regs[0]) ... KVM_REG_ARM_CORE_REG(regs.regs[30]): case KVM_REG_ARM_CORE_REG(regs.sp): case KVM_REG_ARM_CORE_REG(regs.pc): case KVM_REG_ARM_CORE_REG(regs.pstate): case KVM_REG_ARM_CORE_REG(sp_el1): case KVM_REG_ARM_CORE_REG(elr_el1): case KVM_REG_ARM_CORE_REG(spsr[0]) ... KVM_REG_ARM_CORE_REG(spsr[KVM_NR_SPSR - 1]): size = sizeof(__u64); break; case KVM_REG_ARM_CORE_REG(fp_regs.vregs[0]) ... KVM_REG_ARM_CORE_REG(fp_regs.vregs[31]): size = sizeof(__uint128_t); break; case KVM_REG_ARM_CORE_REG(fp_regs.fpsr): case KVM_REG_ARM_CORE_REG(fp_regs.fpcr): size = sizeof(__u32); break; default: return -EINVAL; } if (KVM_REG_SIZE(reg->id) == size && IS_ALIGNED(off, size / sizeof(__u32))) return 0; return -EINVAL; } Commit Message: arm64: KVM: Sanitize PSTATE.M when being set from userspace Not all execution modes are valid for a guest, and some of them depend on what the HW actually supports. Let's verify that what userspace provides is compatible with both the VM settings and the HW capabilities. Cc: <stable@vger.kernel.org> Fixes: 0d854a60b1d7 ("arm64: KVM: enable initialization of a 32bit vcpu") Reviewed-by: Christoffer Dall <christoffer.dall@arm.com> Reviewed-by: Mark Rutland <mark.rutland@arm.com> Reviewed-by: Dave Martin <Dave.Martin@arm.com> Signed-off-by: Marc Zyngier <marc.zyngier@arm.com> Signed-off-by: Will Deacon <will.deacon@arm.com> CWE ID: CWE-20
0
15,031
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; struct ipt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, AF_INET, name), "iptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ xt_entry_foreach(iter, oldinfo->entries, oldinfo->size) cleanup_entry(iter, net); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-119
0
7,916
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr; char prefix[33]; // Prefix for each color name char suffix[33]; // Suffix for each color name int i, nColors; nColors = cmsNamedColorCount(NamedColorList); if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, nColors)) return FALSE; if (!_cmsWriteUInt32Number(io, NamedColorList ->ColorantCount)) return FALSE; strncpy(prefix, (const char*) NamedColorList->Prefix, 32); strncpy(suffix, (const char*) NamedColorList->Suffix, 32); suffix[32] = prefix[32] = 0; if (!io ->Write(io, 32, prefix)) return FALSE; if (!io ->Write(io, 32, suffix)) return FALSE; for (i=0; i < nColors; i++) { cmsUInt16Number PCS[3]; cmsUInt16Number Colorant[cmsMAXCHANNELS]; char Root[33]; if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0; Root[32] = 0; if (!io ->Write(io, 32 , Root)) return FALSE; if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE; if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug CWE ID: CWE-125
0
27,913
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void nfc_llcp_rx_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, rx_work); struct sk_buff *skb; skb = local->rx_pending; if (skb == NULL) { pr_debug("No pending SKB\n"); return; } __net_timestamp(skb); nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_RX); nfc_llcp_rx_skb(local, skb); schedule_work(&local->tx_work); kfree_skb(local->rx_pending); local->rx_pending = NULL; } Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
0
24,083
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void OutOfProcessInstance::OnGeometryChanged(double old_zoom, float old_device_scale) { if (zoom_ != old_zoom || device_scale_ != old_device_scale) engine_->ZoomUpdated(zoom_ * device_scale_); available_area_ = pp::Rect(plugin_size_); int doc_width = GetDocumentPixelWidth(); if (doc_width < available_area_.width()) { available_area_.Offset((available_area_.width() - doc_width) / 2, 0); available_area_.set_width(doc_width); } int bottom_of_document = GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_); if (bottom_of_document < available_area_.height()) available_area_.set_height(bottom_of_document); CalculateBackgroundParts(); engine_->PageOffsetUpdated(available_area_.point()); engine_->PluginSizeUpdated(available_area_.size()); if (!document_size_.GetArea()) return; paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_)); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20
0
13,837
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ProcXFixesHideCursor(ClientPtr client) { WindowPtr pWin; CursorHideCountPtr pChc; REQUEST(xXFixesHideCursorReq); int ret; REQUEST_SIZE_MATCH(xXFixesHideCursorReq); ret = dixLookupResourceByType((void **) &pWin, stuff->window, RT_WINDOW, client, DixGetAttrAccess); if (ret != Success) { client->errorValue = stuff->window; return ret; } /* * Has client hidden the cursor before on this screen? * If so, just increment the count. */ pChc = findCursorHideCount(client, pWin->drawable.pScreen); if (pChc != NULL) { pChc->hideCount++; return Success; } /* * This is the first time this client has hid the cursor * for this screen. */ ret = XaceHook(XACE_SCREEN_ACCESS, client, pWin->drawable.pScreen, DixHideAccess); if (ret != Success) return ret; ret = createCursorHideCount(client, pWin->drawable.pScreen); if (ret == Success) { DeviceIntPtr dev; for (dev = inputInfo.devices; dev; dev = dev->next) { if (IsMaster(dev) && IsPointerDevice(dev)) CursorDisplayCursor(dev, pWin->drawable.pScreen, CursorCurrent[dev->id]); } } return ret; } Commit Message: CWE ID: CWE-20
0
2,052