prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
{
Document* document = contextElement->document();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
if (document->isHTMLDocument()) {
fragment->parseHTML(markup, contextElement);
return fragment;
}
bool wasValid = fragment->parseXML(markup, contextElement);
if (!wasValid) {
ec = INVALID_STATE_ERR;
return 0;
}
return fragment.release();
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Target: 1
Example 2:
Code: void SetProfile(Profile* profile) {
pref_registrar_.reset(new PrefChangeRegistrar);
pref_registrar_->Init(profile->GetPrefs());
pref_registrar_->Add(prefs::kUse24HourClock, this);
pref_registrar_->Add(prefs::kLanguageXkbRemapSearchKeyTo, this);
UpdateClockType(profile->GetPrefs());
search_key_mapped_to_ =
profile->GetPrefs()->GetInteger(prefs::kLanguageXkbRemapSearchKeyTo);
if (gdata::util::IsGDataAvailable(profile)) {
GDataSystemService* system_service =
GDataSystemServiceFactory::FindForProfile(profile);
if (!system_service || !system_service->file_system())
return;
system_service->file_system()->GetOperationRegistry()->
AddObserver(this);
}
}
Commit Message: Use display_email() for Uber Tray messages.
BUG=124087
TEST=manually
Review URL: https://chromiumcodereview.appspot.com/10388171
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137721 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int handle_popc(u32 insn, struct pt_regs *regs)
{
u64 value;
int ret, i, rd = ((insn >> 25) & 0x1f);
int from_kernel = (regs->tstate & TSTATE_PRIV) != 0;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
if (insn & 0x2000) {
maybe_flush_windows(0, 0, rd, from_kernel);
value = sign_extend_imm13(insn);
} else {
maybe_flush_windows(0, insn & 0x1f, rd, from_kernel);
value = fetch_reg(insn & 0x1f, regs);
}
for (ret = 0, i = 0; i < 16; i++) {
ret += popc_helper[value & 0xf];
value >>= 4;
}
if (rd < 16) {
if (rd)
regs->u_regs[rd] = ret;
} else {
if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
put_user(ret, &win32->locals[rd - 16]);
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
put_user(ret, &win->locals[rd - 16]);
}
}
advance(regs);
return 1;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void XSSAuditor::Init(Document* document,
XSSAuditorDelegate* auditor_delegate) {
DCHECK(IsMainThread());
if (state_ != kUninitialized)
return;
state_ = kFilteringTokens;
if (Settings* settings = document->GetSettings())
is_enabled_ = settings->GetXSSAuditorEnabled();
if (!is_enabled_)
return;
document_url_ = document->Url().Copy();
if (!document->GetFrame()) {
is_enabled_ = false;
return;
}
if (document_url_.IsEmpty()) {
is_enabled_ = false;
return;
}
if (document_url_.ProtocolIsData()) {
is_enabled_ = false;
return;
}
if (document->Encoding().IsValid())
encoding_ = document->Encoding();
if (DocumentLoader* document_loader =
document->GetFrame()->Loader().GetDocumentLoader()) {
const AtomicString& header_value =
document_loader->GetResponse().HttpHeaderField(
HTTPNames::X_XSS_Protection);
String error_details;
unsigned error_position = 0;
String report_url;
KURL xss_protection_report_url;
ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader(
header_value, error_details, error_position, report_url);
if (xss_protection_header == kAllowReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled);
else if (xss_protection_header == kFilterReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter);
else if (xss_protection_header == kBlockReflectedXSS)
UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock);
else if (xss_protection_header == kReflectedXSSInvalid)
UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid);
did_send_valid_xss_protection_header_ =
xss_protection_header != kReflectedXSSUnset &&
xss_protection_header != kReflectedXSSInvalid;
if ((xss_protection_header == kFilterReflectedXSS ||
xss_protection_header == kBlockReflectedXSS) &&
!report_url.IsEmpty()) {
xss_protection_report_url = document->CompleteURL(report_url);
if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(),
xss_protection_report_url)) {
error_details = "insecure reporting URL for secure page";
xss_protection_header = kReflectedXSSInvalid;
xss_protection_report_url = KURL();
}
}
if (xss_protection_header == kReflectedXSSInvalid) {
document->AddConsoleMessage(ConsoleMessage::Create(
kSecurityMessageSource, kErrorMessageLevel,
"Error parsing header X-XSS-Protection: " + header_value + ": " +
error_details + " at character position " +
String::Format("%u", error_position) +
". The default protections will be applied."));
}
xss_protection_ = xss_protection_header;
if (xss_protection_ == kReflectedXSSInvalid ||
xss_protection_ == kReflectedXSSUnset) {
xss_protection_ = kBlockReflectedXSS;
}
if (auditor_delegate)
auditor_delegate->SetReportURL(xss_protection_report_url.Copy());
EncodedFormData* http_body = document_loader->GetRequest().HttpBody();
if (http_body && !http_body->IsEmpty())
http_body_as_string_ = http_body->FlattenToString();
}
SetEncoding(encoding_);
}
Commit Message: Restrict the xss audit report URL to same origin
BUG=441275
[email protected],[email protected]
Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d
Reviewed-on: https://chromium-review.googlesource.com/768367
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516666}
CWE ID: CWE-79
Target: 1
Example 2:
Code: sctp_disposition_t sctp_sf_do_9_2_shutdown_ack(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
Commit Message: net: sctp: fix remote memory pressure from excessive queueing
This scenario is not limited to ASCONF, just taken as one
example triggering the issue. When receiving ASCONF probes
in the form of ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------>
[...]
---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------>
... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed
ASCONFs and have increasing serial numbers, we process such
ASCONF chunk(s) marked with !end_of_packet and !singleton,
since we have not yet reached the SCTP packet end. SCTP does
only do verification on a chunk by chunk basis, as an SCTP
packet is nothing more than just a container of a stream of
chunks which it eats up one by one.
We could run into the case that we receive a packet with a
malformed tail, above marked as trailing JUNK. All previous
chunks are here goodformed, so the stack will eat up all
previous chunks up to this point. In case JUNK does not fit
into a chunk header and there are no more other chunks in
the input queue, or in case JUNK contains a garbage chunk
header, but the encoded chunk length would exceed the skb
tail, or we came here from an entirely different scenario
and the chunk has pdiscard=1 mark (without having had a flush
point), it will happen, that we will excessively queue up
the association's output queue (a correct final chunk may
then turn it into a response flood when flushing the
queue ;)): I ran a simple script with incremental ASCONF
serial numbers and could see the server side consuming
excessive amount of RAM [before/after: up to 2GB and more].
The issue at heart is that the chunk train basically ends
with !end_of_packet and !singleton markers and since commit
2e3216cd54b1 ("sctp: Follow security requirement of responding
with 1 packet") therefore preventing an output queue flush
point in sctp_do_sm() -> sctp_cmd_interpreter() on the input
chunk (chunk = event_arg) even though local_cork is set,
but its precedence has changed since then. In the normal
case, the last chunk with end_of_packet=1 would trigger the
queue flush to accommodate possible outgoing bundling.
In the input queue, sctp_inq_pop() seems to do the right thing
in terms of discarding invalid chunks. So, above JUNK will
not enter the state machine and instead be released and exit
the sctp_assoc_bh_rcv() chunk processing loop. It's simply
the flush point being missing at loop exit. Adding a try-flush
approach on the output queue might not work as the underlying
infrastructure might be long gone at this point due to the
side-effect interpreter run.
One possibility, albeit a bit of a kludge, would be to defer
invalid chunk freeing into the state machine in order to
possibly trigger packet discards and thus indirectly a queue
flush on error. It would surely be better to discard chunks
as in the current, perhaps better controlled environment, but
going back and forth, it's simply architecturally not possible.
I tried various trailing JUNK attack cases and it seems to
look good now.
Joint work with Vlad Yasevich.
Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PresentationConnection* PresentationConnection::take(
PresentationController* controller,
const WebPresentationSessionInfo& sessionInfo,
PresentationRequest* request) {
ASSERT(controller);
ASSERT(request);
PresentationConnection* connection = new PresentationConnection(
controller->frame(), sessionInfo.id, sessionInfo.url);
controller->registerConnection(connection);
auto* event = PresentationConnectionAvailableEvent::create(
EventTypeNames::connectionavailable, connection);
TaskRunnerHelper::get(TaskType::Presentation, request->getExecutionContext())
->postTask(BLINK_FROM_HERE,
WTF::bind(&PresentationConnection::dispatchEventAsync,
wrapPersistent(request), wrapPersistent(event)));
return connection;
}
Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures
Add layout test.
1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead.
BUG=697719
Review-Url: https://codereview.chromium.org/2730123003
Cr-Commit-Position: refs/heads/master@{#455225}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void PaymentRequest::RespondToCanMakePaymentQuery(bool can_make_payment,
bool warn_localhost_or_file) {
mojom::CanMakePaymentQueryResult positive =
warn_localhost_or_file
? mojom::CanMakePaymentQueryResult::WARNING_CAN_MAKE_PAYMENT
: mojom::CanMakePaymentQueryResult::CAN_MAKE_PAYMENT;
mojom::CanMakePaymentQueryResult negative =
warn_localhost_or_file
? mojom::CanMakePaymentQueryResult::WARNING_CANNOT_MAKE_PAYMENT
: mojom::CanMakePaymentQueryResult::CANNOT_MAKE_PAYMENT;
client_->OnCanMakePayment(can_make_payment ? positive : negative);
journey_logger_.SetCanMakePaymentValue(can_make_payment);
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xmlRecoverDoc(const xmlChar *cur) {
return(xmlSAXParseDoc(NULL, cur, 1));
}
Commit Message: Detect infinite recursion in parameter entities
When expanding a parameter entity in a DTD, infinite recursion could
lead to an infinite loop or memory exhaustion.
Thanks to Wei Lei for the first of many reports.
Fixes bug 759579.
CWE ID: CWE-835
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
Commit Message: NTP: cap number of notifications/day
1 by default; Finch-configurable.
BUG=689465
Review-Url: https://codereview.chromium.org/2691023002
Cr-Commit-Position: refs/heads/master@{#450389}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void InspectorNetworkAgent::MarkResourceAsCached(unsigned long identifier) {
GetFrontend()->requestServedFromCache(
IdentifiersFactory::RequestId(identifier));
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: String RenderLayerCompositor::debugName(const GraphicsLayer* graphicsLayer)
{
String name;
if (graphicsLayer == m_rootContentLayer.get()) {
name = "Content Root Layer";
#if USE(RUBBER_BANDING)
} else if (graphicsLayer == m_layerForOverhangShadow.get()) {
name = "Overhang Areas Shadow";
#endif
} else if (graphicsLayer == m_overflowControlsHostLayer.get()) {
name = "Overflow Controls Host Layer";
} else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
name = "Horizontal Scrollbar Layer";
} else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
name = "Vertical Scrollbar Layer";
} else if (graphicsLayer == m_layerForScrollCorner.get()) {
name = "Scroll Corner Layer";
} else if (graphicsLayer == m_containerLayer.get()) {
name = "Frame Clipping Layer";
} else if (graphicsLayer == m_scrollLayer.get()) {
name = "Frame Scrolling Layer";
} else {
ASSERT_NOT_REACHED();
}
return name;
}
Commit Message: Disable some more query compositingState asserts.
This gets the tests passing again on Mac. See the bug for the stacktrace.
A future patch will need to actually fix the incorrect reading of
compositingState.
BUG=343179
Review URL: https://codereview.chromium.org/162153002
git-svn-id: svn://svn.chromium.org/blink/trunk@167069 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UseCounterPageLoadMetricsObserver::GetAllowedUkmFeatures() {
static base::NoDestructor<UseCounterPageLoadMetricsObserver::UkmFeatureList>
opt_in_features(std::initializer_list<WebFeature>({
WebFeature::kNavigatorVibrate,
WebFeature::kNavigatorVibrateSubFrame,
WebFeature::kTouchEventPreventedNoTouchAction,
WebFeature::kTouchEventPreventedForcedDocumentPassiveNoTouchAction,
WebFeature::kDataUriHasOctothorpe,
WebFeature::kApplicationCacheManifestSelectInsecureOrigin,
WebFeature::kApplicationCacheManifestSelectSecureOrigin,
WebFeature::kMixedContentAudio,
WebFeature::kMixedContentImage,
WebFeature::kMixedContentVideo,
WebFeature::kMixedContentPlugin,
WebFeature::kOpenerNavigationWithoutGesture,
WebFeature::kUsbRequestDevice,
WebFeature::kXMLHttpRequestSynchronous,
WebFeature::kPaymentHandler,
WebFeature::kPaymentRequestShowWithoutGesture,
WebFeature::kHTMLImports,
WebFeature::kHTMLImportsHasStyleSheets,
WebFeature::kElementCreateShadowRoot,
WebFeature::kDocumentRegisterElement,
WebFeature::kCredentialManagerCreatePublicKeyCredential,
WebFeature::kCredentialManagerGetPublicKeyCredential,
WebFeature::kCredentialManagerMakePublicKeyCredentialSuccess,
WebFeature::kCredentialManagerGetPublicKeyCredentialSuccess,
WebFeature::kV8AudioContext_Constructor,
WebFeature::kElementAttachShadow,
WebFeature::kElementAttachShadowOpen,
WebFeature::kElementAttachShadowClosed,
WebFeature::kCustomElementRegistryDefine,
WebFeature::kTextToSpeech_Speak,
WebFeature::kTextToSpeech_SpeakDisallowedByAutoplay,
WebFeature::kCSSEnvironmentVariable,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetTop,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetLeft,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetRight,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetBottom,
WebFeature::kMediaControlsDisplayCutoutGesture,
WebFeature::kPolymerV1Detected,
WebFeature::kPolymerV2Detected,
WebFeature::kFullscreenSecureOrigin,
WebFeature::kFullscreenInsecureOrigin,
WebFeature::kPrefixedVideoEnterFullscreen,
WebFeature::kPrefixedVideoExitFullscreen,
WebFeature::kPrefixedVideoEnterFullScreen,
WebFeature::kPrefixedVideoExitFullScreen,
WebFeature::kDocumentLevelPassiveDefaultEventListenerPreventedWheel,
WebFeature::kDocumentDomainBlockedCrossOriginAccess,
WebFeature::kDocumentDomainEnabledCrossOriginAccess,
WebFeature::kSuppressHistoryEntryWithoutUserGesture,
WebFeature::kCursorImageGT32x32,
WebFeature::kCursorImageLE32x32,
WebFeature::kHistoryPushState,
WebFeature::kHistoryReplaceState,
WebFeature::kCursorImageGT64x64,
WebFeature::kAdClick,
WebFeature::kUpdateWithoutShippingOptionOnShippingAddressChange,
WebFeature::kUpdateWithoutShippingOptionOnShippingOptionChange,
WebFeature::kSignedExchangeInnerResponseInMainFrame,
WebFeature::kSignedExchangeInnerResponseInSubFrame,
WebFeature::kWebShareShare,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithUserGesture,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithoutUserGesture,
WebFeature::kNavigationDownloadInSandboxWithUserGesture,
WebFeature::kNavigationDownloadInSandboxWithoutUserGesture,
WebFeature::kDownloadInAdFrameWithUserGesture,
WebFeature::kDownloadInAdFrameWithoutUserGesture,
WebFeature::kOpenWebDatabase,
WebFeature::kV8MediaCapabilities_DecodingInfo_Method,
}));
return *opt_in_features;
}
Commit Message: Add kOpenerNavigationDownloadCrossOriginNoGesture to UKM whitelist
Bug: 632514
Change-Id: Ibd09c4d8635873e02f9b484ec720b71ae6e3588f
Reviewed-on: https://chromium-review.googlesource.com/c/1399521
Reviewed-by: Bryan McQuade <[email protected]>
Commit-Queue: Charlie Harrison <[email protected]>
Cr-Commit-Position: refs/heads/master@{#620513}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void vmw_hw_surface_destroy(struct vmw_resource *res)
{
struct vmw_private *dev_priv = res->dev_priv;
struct vmw_surface *srf;
void *cmd;
if (res->func->destroy == vmw_gb_surface_destroy) {
(void) vmw_gb_surface_destroy(res);
return;
}
if (res->id != -1) {
cmd = vmw_fifo_reserve(dev_priv, vmw_surface_destroy_size());
if (unlikely(!cmd)) {
DRM_ERROR("Failed reserving FIFO space for surface "
"destruction.\n");
return;
}
vmw_surface_destroy_encode(res->id, cmd);
vmw_fifo_commit(dev_priv, vmw_surface_destroy_size());
/*
* used_memory_size_atomic, or separate lock
* to avoid taking dev_priv::cmdbuf_mutex in
* the destroy path.
*/
mutex_lock(&dev_priv->cmdbuf_mutex);
srf = vmw_res_to_srf(res);
dev_priv->used_memory_size -= res->backup_size;
mutex_unlock(&dev_priv->cmdbuf_mutex);
}
vmw_fifo_resource_dec(dev_priv);
}
Commit Message: drm/vmwgfx: Make sure backup_handle is always valid
When vmw_gb_surface_define_ioctl() is called with an existing buffer,
we end up returning an uninitialized variable in the backup_handle.
The fix is to first initialize backup_handle to 0 just to be sure, and
second, when a user-provided buffer is found, we will use the
req->buffer_handle as the backup_handle.
Cc: <[email protected]>
Reported-by: Murray McAllister <[email protected]>
Signed-off-by: Sinclair Yeh <[email protected]>
Reviewed-by: Deepak Rawat <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: CStarter::Config()
{
if( Execute ) {
free( Execute );
}
if( (Execute = param("EXECUTE")) == NULL ) {
if( is_gridshell ) {
Execute = strdup( orig_cwd );
} else {
EXCEPT("Execute directory not specified in config file.");
}
}
if (!m_configured) {
bool ps = privsep_enabled();
bool gl = param_boolean("GLEXEC_JOB", false);
#if !defined(LINUX)
dprintf(D_ALWAYS,
"GLEXEC_JOB not supported on this platform; "
"ignoring\n");
gl = false;
#endif
if (ps && gl) {
EXCEPT("can't support both "
"PRIVSEP_ENABLED and GLEXEC_JOB");
}
if (ps) {
m_privsep_helper = new CondorPrivSepHelper;
ASSERT(m_privsep_helper != NULL);
}
else if (gl) {
#if defined(LINUX)
m_privsep_helper = new GLExecPrivSepHelper;
ASSERT(m_privsep_helper != NULL);
#endif
}
}
jic->config();
m_configured = true;
}
Commit Message:
CWE ID: CWE-134
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NetworkHandler::GetAllCookies(
std::unique_ptr<GetAllCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveAllCookiesOnIO, retriever,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext())));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: AP_DECLARE(int) ap_is_initial_req(request_rec *r)
{
return (r->main == NULL) /* otherwise, this is a sub-request */
&& (r->prev == NULL); /* otherwise, this is an internal redirect */
}
Commit Message: SECURITY: CVE-2015-3183 (cve.mitre.org)
Replacement of ap_some_auth_required (unusable in Apache httpd 2.4)
with new ap_some_authn_required and ap_force_authn hook.
Submitted by: breser
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
{
const char
*comment;
int
bits;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
x;
register unsigned char
*q;
size_t
bits_per_pixel,
literal,
packets,
packet_size,
repeat;
ssize_t
y;
unsigned char
*buffer,
*runlength,
*scanline;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
if ((image -> colors <= 2 ) ||
(GetImageType(image,&image->exception ) == BilevelType)) {
bits_per_pixel=1;
} else if (image->colors <= 4) {
bits_per_pixel=2;
} else if (image->colors <= 8) {
bits_per_pixel=3;
} else {
bits_per_pixel=4;
}
(void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info));
(void) CopyMagickString(pdb_info.name,image_info->filename,
sizeof(pdb_info.name));
pdb_info.attributes=0;
pdb_info.version=0;
pdb_info.create_time=time(NULL);
pdb_info.modify_time=pdb_info.create_time;
pdb_info.archive_time=0;
pdb_info.modify_number=0;
pdb_info.application_info=0;
pdb_info.sort_info=0;
(void) CopyMagickMemory(pdb_info.type,"vIMG",4);
(void) CopyMagickMemory(pdb_info.id,"View",4);
pdb_info.seed=0;
pdb_info.next_record=0;
comment=GetImageProperty(image,"comment");
pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
(void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
(void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));
pdb_image.version=1; /* RLE Compressed */
switch (bits_per_pixel)
{
case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */
case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */
default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */
}
pdb_image.reserved_1=0;
pdb_image.note=0;
pdb_image.x_last=0;
pdb_image.y_last=0;
pdb_image.reserved_2=0;
pdb_image.x_anchor=(unsigned short) 0xffff;
pdb_image.y_anchor=(unsigned short) 0xffff;
pdb_image.width=(short) image->columns;
if (image->columns % 16)
pdb_image.width=(short) (16*(image->columns/16+1));
pdb_image.height=(short) image->rows;
packets=((bits_per_pixel*image->columns+7)/8);
runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets,
image->rows*sizeof(*runlength));
if (runlength == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
packet_size=(size_t) (image->depth > 8 ? 2: 1);
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Convert to GRAY raster scanline.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
bits=8/(int) bits_per_pixel-1; /* start at most significant bits */
literal=0;
repeat=0;
q=runlength;
buffer[0]=0x00;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
GrayQuantum,scanline,&image->exception);
for (x=0; x < (ssize_t) pdb_image.width; x++)
{
if (x < (ssize_t) image->columns)
buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
(8-bits_per_pixel) << bits*bits_per_pixel;
bits--;
if (bits < 0)
{
if (((literal+repeat) > 0) &&
(buffer[literal+repeat] == buffer[literal+repeat-1]))
{
if (repeat == 0)
{
literal--;
repeat++;
}
repeat++;
if (0x7f < repeat)
{
q=EncodeRLE(q,buffer,literal,repeat);
literal=0;
repeat=0;
}
}
else
{
if (repeat >= 2)
literal+=repeat;
else
{
q=EncodeRLE(q,buffer,literal,repeat);
buffer[0]=buffer[literal+repeat];
literal=0;
}
literal++;
repeat=0;
if (0x7f < literal)
{
q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
(void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
literal-=0x80;
}
}
bits=8/(int) bits_per_pixel-1;
buffer[literal+repeat]=0x00;
}
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
q=EncodeRLE(q,buffer,literal,repeat);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
quantum_info=DestroyQuantumInfo(quantum_info);
/*
Write the Image record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8*
pdb_info.number_records));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,0);
if (pdb_info.number_records > 1)
{
/*
Write the comment record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
runlength));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,1);
}
/*
Write the Image data.
*/
(void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)
pdb_image.name);
(void) WriteBlobByte(image,(unsigned char) pdb_image.version);
(void) WriteBlobByte(image,pdb_image.type);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
(void) WriteBlobMSBShort(image,pdb_image.x_anchor);
(void) WriteBlobMSBShort(image,pdb_image.y_anchor);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
(void) WriteBlob(image,(size_t) (q-runlength),runlength);
runlength=(unsigned char *) RelinquishMagickMemory(runlength);
if (pdb_info.number_records > 1)
(void) WriteBlobString(image,comment);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out)
{
void **out = (void **)_out;
struct asn1_data *data = asn1_init(mem_ctx);
struct dsdb_openldap_dereference_result_control *control;
struct dsdb_openldap_dereference_result **r = NULL;
int i = 0;
if (!data) return false;
control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);
if (!control) return false;
if (!asn1_load(data, in)) {
return false;
}
control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);
if (!control) {
return false;
}
if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {
return false;
}
while (asn1_tag_remaining(data) > 0) {
r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2);
if (!r) {
return false;
}
r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result);
if (!r[i]) {
return false;
}
if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {
return false;
}
asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute);
asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn);
if (asn1_peek_tag(data, ASN1_CONTEXT(0))) {
if (!asn1_start_tag(data, ASN1_CONTEXT(0))) {
return false;
}
ldap_decode_attribs_bare(r, data, &r[i]->attributes,
&r[i]->num_attributes);
if (!asn1_end_tag(data)) {
return false;
}
}
if (!asn1_end_tag(data)) {
return false;
}
i++;
r[i] = NULL;
}
if (!asn1_end_tag(data)) {
return false;
}
control->attributes = r;
*out = control;
return true;
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: static struct nft_rule *__nf_tables_rule_lookup(const struct nft_chain *chain,
u64 handle)
{
struct nft_rule *rule;
list_for_each_entry(rule, &chain->rules, list) {
if (handle == rule->handle)
return rule;
}
return ERR_PTR(-ENOENT);
}
Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies
Jumping between chains doesn't mix well with flush ruleset. Rules
from a different chain and set elements may still refer to us.
[ 353.373791] ------------[ cut here ]------------
[ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159!
[ 353.373896] invalid opcode: 0000 [#1] SMP
[ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi
[ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98
[ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010
[...]
[ 353.375018] Call Trace:
[ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540
[ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0
[ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0
[ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790
[ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0
[ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70
[ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30
[ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0
[ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400
[ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90
[ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20
[ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0
[ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80
[ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d
[ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20
[ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b
Release objects in this order: rules -> sets -> chains -> tables, to
make sure no references to chains are held anymore.
Reported-by: Asbjoern Sloth Toennesen <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-19
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump;
u_int offset;
u_int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
if (tlen < sizeof(const struct lmp_common_header)) {
ND_PRINT((ndo, " (too short)"));
return;
}
if (tlen > len) {
ND_PRINT((ndo, " (too long)"));
tlen = len;
}
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
if (lmp_obj_len < 4) {
ND_PRINT((ndo, " (too short)"));
return;
}
if ((lmp_obj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
return;
}
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
if (obj_tlen != 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
break;
case LMP_CTYPE_UNMD:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)"
"\n\t Remote Link-ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
case LMP_CTYPE_IPV6:
if (obj_tlen < 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36))
hexdump=TRUE;
break;
case LMP_CTYPE_UNMD:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)"
"\n\t Remote Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 20) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
/* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */
while (offset+20 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));
offset+=20;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
while (offset+16 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=16;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
link_type = EXTRACT_8BITS(obj_tptr);
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
switch (link_type) {
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 2))));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 7))));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
Commit Message: (for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check
In lmp_print_data_link_subobjs().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PromoResourceService::PostNotification(int64 delay_ms) {
if (web_resource_update_scheduled_)
return;
if (delay_ms > 0) {
web_resource_update_scheduled_ = true;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: count_resources(pe_working_set_t * data_set, resource_t * rsc)
{
int count = 0;
GListPtr gIter = NULL;
if (rsc == NULL) {
gIter = data_set->resources;
} else if (rsc->children) {
gIter = rsc->children;
} else {
return is_not_set(rsc->flags, pe_rsc_orphan);
}
for (; gIter != NULL; gIter = gIter->next) {
count += count_resources(data_set, gIter->data);
}
return count;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: base::string16 FormatBookmarkURLForDisplay(const GURL& url) {
return url_formatter::FormatUrl(
url, url_formatter::kFormatUrlOmitAll &
~url_formatter::kFormatUrlOmitUsernamePassword,
net::UnescapeRule::SPACES, nullptr, nullptr, nullptr);
}
Commit Message: Prevent interpretating userinfo as url scheme when editing bookmarks
Chrome's Edit Bookmark dialog formats urls for display such that a
url of http://javascript:[email protected] is later converted to a
javascript url scheme, allowing persistence of a script injection
attack within the user's bookmarks.
This fix prevents such misinterpretations by always showing the
scheme when a userinfo component is present within the url.
BUG=639126
Review-Url: https://codereview.chromium.org/2368593002
Cr-Commit-Position: refs/heads/master@{#422467}
CWE ID: CWE-79
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void build_l4proto_sctp(const struct nf_conntrack *ct, struct nethdr *n)
{
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
if (!nfct_attr_is_set(ct, ATTR_SCTP_STATE))
return;
ct_build_u8(ct, ATTR_SCTP_STATE, n, NTA_SCTP_STATE);
ct_build_u32(ct, ATTR_SCTP_VTAG_ORIG, n, NTA_SCTP_VTAG_ORIG);
ct_build_u32(ct, ATTR_SCTP_VTAG_REPL, n, NTA_SCTP_VTAG_REPL);
}
Commit Message:
CWE ID: CWE-17
Target: 1
Example 2:
Code: static int afiucv_hs_callback_fin(struct sock *sk, struct sk_buff *skb)
{
struct iucv_sock *iucv = iucv_sk(sk);
/* other end of connection closed */
if (!iucv)
goto out;
bh_lock_sock(sk);
if (sk->sk_state == IUCV_CONNECTED) {
sk->sk_state = IUCV_DISCONN;
sk->sk_state_change(sk);
}
bh_unlock_sock(sk);
out:
kfree_skb(skb);
return NET_RX_SUCCESS;
}
Commit Message: iucv: Fix missing msg_namelen update in iucv_sock_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 iucv_sock_recvmsg() not filling the msg_name in case it was set.
Cc: Ursula Braun <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
Commit Message: Remove use of SEE_MASK_FLAG_NO_UI from Chrome Windows installer.
This flag was originally added to ui::base::win to suppress a specific
error message when attempting to open a file via the shell using the
"open" verb. The flag has additional side-effects and shouldn't be used
when invoking ShellExecute().
[email protected]
Bug: 819809
Change-Id: I7db2344982dd206c85a73928e906c21e06a47a9e
Reviewed-on: https://chromium-review.googlesource.com/966964
Commit-Queue: Greg Thompson <[email protected]>
Reviewed-by: Greg Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544012}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
if (end < start) {
return false;
}
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
Commit Message: Add error logging on invalid cmap - DO NOT MERGE
This patch logs instances of fonts with invalid cmap tables.
Bug: 25645298
Bug: 26413177
Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool IsValidFileExtension(const String& type) {
if (type.length() < 2)
return false;
return type[0] == '.';
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ~BlinkTestEnvironmentScope()
{
content::TearDownBlinkTestEnvironment();
}
Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used.
These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect.
BUG=552749
Review URL: https://codereview.chromium.org/1419293005
Cr-Commit-Position: refs/heads/master@{#359229}
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GfxImageColorMap::getGrayLine(Guchar *in, Guchar *out, int length) {
int i, j;
Guchar *inp, *tmp_line;
switch (colorSpace->getMode()) {
case csIndexed:
case csSeparation:
tmp_line = (Guchar *) gmalloc (length * nComps2);
for (i = 0; i < length; i++) {
for (j = 0; j < nComps2; j++) {
tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j];
}
}
colorSpace2->getGrayLine(tmp_line, out, length);
gfree (tmp_line);
break;
default:
inp = in;
for (j = 0; j < length; j++)
for (i = 0; i < nComps; i++) {
*inp = byte_lookup[*inp * nComps + i];
inp++;
}
colorSpace->getGrayLine(in, out, length);
break;
}
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline unsigned start_dir_add(struct inode *dir)
{
for (;;) {
unsigned n = dir->i_dir_seq;
if (!(n & 1) && cmpxchg(&dir->i_dir_seq, n, n + 1) == n)
return n;
cpu_relax();
}
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int SelectionDialog(char* title, char* message, char** choices, int size)
{
int ret;
dialog_showing++;
szMessageTitle = title;
szMessageText = message;
szDialogItem = choices;
nDialogItems = size;
ret = (int)MyDialogBox(hMainInstance, IDD_SELECTION, hMainDialog, SelectionCallback);
dialog_showing--;
return ret;
}
Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768
* This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as
it is described per its revision 11, which is the latest revision at the time of this commit,
by disabling Windows prompts, enacted during signature validation, that allow the user to
bypass the intended signature verification checks.
* It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed
certificate"), which relies on the end-user actively ignoring a Windows prompt that tells
them that the update failed the signature validation whilst also advising against running it,
is being fully addressed, even as the update protocol remains HTTP.
* It also need to be pointed out that the extended delay (48 hours) between the time the
vulnerability was reported and the moment it is fixed in our codebase has to do with
the fact that the reporter chose to deviate from standard security practices by not
disclosing the details of the vulnerability with us, be it publicly or privately,
before creating the cert.org report. The only advance notification we received was a
generic note about the use of HTTP vs HTTPS, which, as have established, is not
immediately relevant to addressing the reported vulnerability.
* Closes #1009
* Note: The other vulnerability scenario described towards the end of #1009, which
doesn't have to do with the "lack of CA checking", will be addressed separately.
CWE ID: CWE-494
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
return -ENODEV;
ops = kvm_device_ops_table[cd->type];
if (ops == NULL)
return -ENODEV;
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
mutex_lock(&kvm->lock);
ret = ops->create(dev, cd->type);
if (ret < 0) {
mutex_unlock(&kvm->lock);
kfree(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
mutex_unlock(&kvm->lock);
if (ops->init)
ops->init(dev);
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
ops->destroy(dev);
mutex_lock(&kvm->lock);
list_del(&dev->vm_node);
mutex_unlock(&kvm->lock);
return ret;
}
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
}
Commit Message: KVM: use after free in kvm_ioctl_create_device()
We should move the ops->destroy(dev) after the list_del(&dev->vm_node)
so that we don't use "dev" after freeing it.
Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock")
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: auth_update_component(struct sc_card *card, struct auth_update_component_info *args)
{
struct sc_apdu apdu;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE + 0x10];
unsigned char ins, p1, p2;
int rv, len;
LOG_FUNC_CALLED(card->ctx);
if (args->len > sizeof(sbuf) || args->len > 0x100)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(card->ctx, "nn %i; len %i", args->component, args->len);
ins = 0xD8;
p1 = args->component;
p2 = 0x04;
len = 0;
sbuf[len++] = args->type;
sbuf[len++] = args->len;
memcpy(sbuf + len, args->data, args->len);
len += args->len;
if (args->type == SC_CARDCTL_OBERTHUR_KEY_DES) {
int outl;
const unsigned char in[8] = {0,0,0,0,0,0,0,0};
unsigned char out[8];
EVP_CIPHER_CTX * ctx = NULL;
if (args->len!=8 && args->len!=24)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL,SC_ERROR_OUT_OF_MEMORY);
p2 = 0;
if (args->len == 24)
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, args->data, NULL);
else
EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, args->data, NULL);
rv = EVP_EncryptUpdate(ctx, out, &outl, in, 8);
EVP_CIPHER_CTX_free(ctx);
if (rv == 0) {
sc_log(card->ctx, "OpenSSL encryption error.");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
sbuf[len++] = 0x03;
memcpy(sbuf + len, out, 3);
len += 3;
}
else {
sbuf[len++] = 0;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, ins, p1, p2);
apdu.cla |= 0x80;
apdu.data = sbuf;
apdu.datalen = len;
apdu.lc = len;
if (args->len == 0x100) {
sbuf[0] = args->type;
sbuf[1] = 0x20;
memcpy(sbuf + 2, args->data, 0x20);
sbuf[0x22] = 0;
apdu.cla |= 0x10;
apdu.data = sbuf;
apdu.datalen = 0x23;
apdu.lc = 0x23;
rv = sc_transmit_apdu(card, &apdu);
apdu.cla &= ~0x10;
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
sbuf[0] = args->type;
sbuf[1] = 0xE0;
memcpy(sbuf + 2, args->data + 0x20, 0xE0);
sbuf[0xE2] = 0;
apdu.data = sbuf;
apdu.datalen = 0xE3;
apdu.lc = 0xE3;
}
rv = sc_transmit_apdu(card, &apdu);
sc_mem_clear(sbuf, sizeof(sbuf));
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(card->ctx, rv);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TabContentsContainerGtk::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type);
WebContentsDestroyed(content::Source<WebContents>(source).ptr());
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
Commit Message: Don't change Document load progress in any page dismissal events.
This can confuse the logic for blocking modal dialogs.
BUG=536652
Review URL: https://codereview.chromium.org/1373113002
Cr-Commit-Position: refs/heads/master@{#351419}
CWE ID: CWE-20
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandleLockDiscardableTextureCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::LockDiscardableTextureCHROMIUM& c =
*static_cast<const volatile gles2::cmds::LockDiscardableTextureCHROMIUM*>(
cmd_data);
GLuint texture_id = c.texture_id;
if (!GetContextGroup()->discardable_manager()->LockTexture(
texture_id, group_->texture_manager())) {
base::debug::DumpWithoutCrashing();
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glLockDiscardableTextureCHROMIUM",
"Texture ID not initialized");
}
return error::kNoError;
}
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 <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static __le32 ext4_xattr_block_csum(struct inode *inode,
sector_t block_nr,
struct ext4_xattr_header *hdr)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__le32 save_csum;
__le64 dsk_block_nr = cpu_to_le64(block_nr);
save_csum = hdr->h_checksum;
hdr->h_checksum = 0;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&dsk_block_nr,
sizeof(dsk_block_nr));
csum = ext4_chksum(sbi, csum, (__u8 *)hdr,
EXT4_BLOCK_SIZE(inode->i_sb));
hdr->h_checksum = save_csum;
return cpu_to_le32(csum);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual InputMethodDescriptor current_input_method() const {
if (current_input_method_.id.empty()) {
return input_method::GetFallbackInputMethodDescriptor();
}
return current_input_method_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
spin_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
spin_unlock(&journal->j_state_lock);
}
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 <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ResourceDispatcherHostImpl::OnShutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
is_shutdown_ = true;
for (PendingRequestList::const_iterator i = pending_requests_.begin();
i != pending_requests_.end(); ++i) {
transferred_navigations_.erase(i->first);
}
STLDeleteValues(&pending_requests_);
update_load_states_timer_.reset();
std::set<ProcessRouteIDs> ids;
for (BlockedRequestMap::const_iterator iter = blocked_requests_map_.begin();
iter != blocked_requests_map_.end(); ++iter) {
std::pair<std::set<ProcessRouteIDs>::iterator, bool> result =
ids.insert(iter->first);
DCHECK(result.second);
}
for (std::set<ProcessRouteIDs>::const_iterator iter = ids.begin();
iter != ids.end(); ++iter) {
CancelBlockedRequestsForRoute(iter->first, iter->second);
}
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
Commit Message: net: fix a kernel infoleak in x25 module
Stack object "dte_facilities" is allocated in x25_rx_call_request(),
which is supposed to be initialized in x25_negotiate_facilities.
However, 5 fields (8 bytes in total) are not initialized. This
object is then copied to userland via copy_to_user, thus infoleak
occurs.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: void MediaStreamDispatcherHost::OnStreamStarted(const std::string& label) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->OnStreamStarted(label);
}
Commit Message: [MediaStream] Pass request ID parameters in the right order for OpenDevice()
Prior to this CL, requester_id and page_request_id parameters were
passed in incorrect order from MediaStreamDispatcherHost to
MediaStreamManager for the OpenDevice() operation, which could lead to
errors.
Bug: 948564
Change-Id: Iadcf3fe26adaac50564102138ce212269cf32d62
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1569113
Reviewed-by: Marina Ciocea <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#651255}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
struct cftype *cftype, s64 cfs_quota_us)
{
return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal)
{
HEVCLocalContext *lc = s->HEVClc;
GetBitContext *gb = &lc->gb;
int ctb_addr_ts, ret;
*gb = nal->gb;
s->nal_unit_type = nal->type;
s->temporal_id = nal->temporal_id;
switch (s->nal_unit_type) {
case HEVC_NAL_VPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_SPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps,
s->apply_defdispwin);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_PPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_SEI_PREFIX:
case HEVC_NAL_SEI_SUFFIX:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_TRAIL_R:
case HEVC_NAL_TRAIL_N:
case HEVC_NAL_TSA_N:
case HEVC_NAL_TSA_R:
case HEVC_NAL_STSA_N:
case HEVC_NAL_STSA_R:
case HEVC_NAL_BLA_W_LP:
case HEVC_NAL_BLA_W_RADL:
case HEVC_NAL_BLA_N_LP:
case HEVC_NAL_IDR_W_RADL:
case HEVC_NAL_IDR_N_LP:
case HEVC_NAL_CRA_NUT:
case HEVC_NAL_RADL_N:
case HEVC_NAL_RADL_R:
case HEVC_NAL_RASL_N:
case HEVC_NAL_RASL_R:
ret = hls_slice_header(s);
if (ret < 0)
return ret;
if (
(s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) ||
(s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) ||
(s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) {
break;
}
if (s->sh.first_slice_in_pic_flag) {
if (s->ref) {
av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n");
goto fail;
}
if (s->max_ra == INT_MAX) {
if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) {
s->max_ra = s->poc;
} else {
if (IS_IDR(s))
s->max_ra = INT_MIN;
}
}
if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) &&
s->poc <= s->max_ra) {
s->is_decoded = 0;
break;
} else {
if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra)
s->max_ra = INT_MIN;
}
s->overlap ++;
ret = hevc_frame_start(s);
if (ret < 0)
return ret;
} else if (!s->ref) {
av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");
goto fail;
}
if (s->nal_unit_type != s->first_nal_type) {
av_log(s->avctx, AV_LOG_ERROR,
"Non-matching NAL types of the VCL NALUs: %d %d\n",
s->first_nal_type, s->nal_unit_type);
return AVERROR_INVALIDDATA;
}
if (!s->sh.dependent_slice_segment_flag &&
s->sh.slice_type != HEVC_SLICE_I) {
ret = ff_hevc_slice_rpl(s);
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING,
"Error constructing the reference lists for the current slice.\n");
goto fail;
}
}
if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) {
ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0);
if (ret < 0)
goto fail;
}
if (s->avctx->hwaccel) {
ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size);
if (ret < 0)
goto fail;
} else {
if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0)
ctb_addr_ts = hls_slice_data_wpp(s, nal);
else
ctb_addr_ts = hls_slice_data(s);
if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) {
s->is_decoded = 1;
}
if (ctb_addr_ts < 0) {
ret = ctb_addr_ts;
goto fail;
}
}
break;
case HEVC_NAL_EOS_NUT:
case HEVC_NAL_EOB_NUT:
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
break;
case HEVC_NAL_AUD:
case HEVC_NAL_FD_NUT:
break;
default:
av_log(s->avctx, AV_LOG_INFO,
"Skipping NAL unit %d\n", s->nal_unit_type);
}
return 0;
fail:
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return ret;
return 0;
}
Commit Message: avcodec/hevcdec: Avoid only partly skiping duplicate first slices
Fixes: NULL pointer dereference and out of array access
Fixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432
Fixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304
This also fixes the return code for explode mode
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: James Almer <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: void RenderFrameImpl::OnCustomContextMenuAction(
const CustomContextMenuContext& custom_context,
unsigned action) {
if (custom_context.request_id) {
ContextMenuClient* client =
pending_context_menus_.Lookup(custom_context.request_id);
if (client)
client->OnMenuAction(custom_context.request_id, action);
} else {
render_view_->webview()->performCustomContextMenuAction(action);
}
}
Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame.
BUG=369553
[email protected]
Review URL: https://codereview.chromium.org/263833020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLES2Implementation::CoverStrokePathInstancedCHROMIUM(
GLsizei num_paths,
GLenum path_name_type,
const GLvoid* paths,
GLuint path_base,
GLenum cover_mode,
GLenum transform_type,
const GLfloat* transform_values) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix()
<< "] glCoverStrokePathInstancedCHROMIUM(" << num_paths
<< ", " << path_name_type << ", " << paths << ", "
<< path_base << ", " << cover_mode << ", "
<< transform_type << ", " << transform_values << ")");
ScopedTransferBufferPtr buffer(helper_, transfer_buffer_);
uint32_t paths_shm_id = 0;
uint32_t paths_offset = 0;
uint32_t transforms_shm_id = 0;
uint32_t transforms_offset = 0;
if (!PrepareInstancedPathCommand(
"glCoverStrokePathInstancedCHROMIUM", num_paths, path_name_type,
paths, transform_type, transform_values, &buffer, &paths_shm_id,
&paths_offset, &transforms_shm_id, &transforms_offset)) {
return;
}
helper_->CoverStrokePathInstancedCHROMIUM(
num_paths, path_name_type, paths_shm_id, paths_offset, path_base,
cover_mode, transform_type, transforms_shm_id, transforms_offset);
CheckGLError();
}
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 <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: shared_memory_handle(const gfx::GpuMemoryBufferHandle& handle) {
if (handle.type != gfx::SHARED_MEMORY_BUFFER &&
handle.type != gfx::DXGI_SHARED_HANDLE &&
handle.type != gfx::ANDROID_HARDWARE_BUFFER)
return mojo::ScopedSharedBufferHandle();
return mojo::WrapSharedMemoryHandle(handle.handle, handle.handle.GetSize(),
false);
}
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 <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void FileBrowserPrivateSearchDriveMetadataFunction::OnEntryDefinitionList(
scoped_ptr<drive::MetadataSearchResultVector> search_result_info_list,
scoped_ptr<EntryDefinitionList> entry_definition_list) {
DCHECK_EQ(search_result_info_list->size(), entry_definition_list->size());
base::ListValue* results_list = new base::ListValue();
for (size_t i = 0; i < entry_definition_list->size(); ++i) {
base::DictionaryValue* result_dict = new base::DictionaryValue();
base::DictionaryValue* entry = new base::DictionaryValue();
entry->SetString(
"fileSystemName", entry_definition_list->at(i).file_system_name);
entry->SetString(
"fileSystemRoot", entry_definition_list->at(i).file_system_root_url);
entry->SetString(
"fileFullPath",
"/" + entry_definition_list->at(i).full_path.AsUTF8Unsafe());
entry->SetBoolean("fileIsDirectory",
entry_definition_list->at(i).is_directory);
result_dict->Set("entry", entry);
result_dict->SetString(
"highlightedBaseName",
search_result_info_list->at(i).highlighted_base_name);
results_list->Append(result_dict);
}
SetResult(results_list);
SendResponse(true);
}
Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery.
Previous Review URL: https://codereview.chromium.org/431293002
BUG=374667
TEST=manually
[email protected], [email protected]
Review URL: https://codereview.chromium.org/433733004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
Commit Message: Add Android SDK version to crash reports.
Bug: 911669
Change-Id: I62a97d76a0b88099a5a42b93463307f03be9b3e2
Reviewed-on: https://chromium-review.googlesource.com/c/1361104
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Peter Conn <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Michael van Ouwerkerk <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615851}
CWE ID: CWE-189
Target: 1
Example 2:
Code: std::string BrowserViewRenderer::ToString() const {
std::string str;
base::StringAppendF(&str, "is_paused: %d ", is_paused_);
base::StringAppendF(&str, "view_visible: %d ", view_visible_);
base::StringAppendF(&str, "window_visible: %d ", window_visible_);
base::StringAppendF(&str, "dip_scale: %f ", dip_scale_);
base::StringAppendF(&str, "page_scale_factor: %f ", page_scale_factor_);
base::StringAppendF(&str, "fallback_tick_pending: %d ",
fallback_tick_pending_);
base::StringAppendF(&str, "view size: %s ", size_.ToString().c_str());
base::StringAppendF(&str, "attached_to_window: %d ", attached_to_window_);
base::StringAppendF(&str,
"global visible rect: %s ",
last_on_draw_global_visible_rect_.ToString().c_str());
base::StringAppendF(
&str, "scroll_offset_dip: %s ", scroll_offset_dip_.ToString().c_str());
base::StringAppendF(&str,
"overscroll_rounding_error_: %s ",
overscroll_rounding_error_.ToString().c_str());
base::StringAppendF(
&str, "on_new_picture_enable: %d ", on_new_picture_enable_);
base::StringAppendF(&str, "clear_view: %d ", clear_view_);
return str;
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: _TIFFmalloc(tmsize_t s)
{
return (malloc((size_t) s));
}
Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not
require malloc() to return NULL pointer if requested allocation
size is zero. Assure that _TIFFmalloc does.
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
{
PNG_CONST PNG_IDAT;
PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
0xff};
PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
int ret;
if (png_ptr == NULL)
return;
png_debug2(1, "in png_read_row (row %lu, pass %d)",
png_ptr->row_number, png_ptr->pass);
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
if (png_ptr->row_number == 0 && png_ptr->pass == 0)
{
/* Check for transforms that have been set but were defined out */
#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
if (png_ptr->transformations & PNG_INVERT_MONO)
png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
if (png_ptr->transformations & PNG_FILLER)
png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
!defined(PNG_READ_PACKSWAP_SUPPORTED)
if (png_ptr->transformations & PNG_PACKSWAP)
png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
if (png_ptr->transformations & PNG_PACK)
png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
if (png_ptr->transformations & PNG_SHIFT)
png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
if (png_ptr->transformations & PNG_BGR)
png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
if (png_ptr->transformations & PNG_SWAP_BYTES)
png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
#endif
}
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* If interlaced and we do not need a new row, combine row and return */
if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
{
switch (png_ptr->pass)
{
case 0:
if (png_ptr->row_number & 0x07)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 1:
if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 2:
if ((png_ptr->row_number & 0x07) != 4)
{
if (dsp_row != NULL && (png_ptr->row_number & 4))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 3:
if ((png_ptr->row_number & 3) || png_ptr->width < 3)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 4:
if ((png_ptr->row_number & 3) != 2)
{
if (dsp_row != NULL && (png_ptr->row_number & 2))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 5:
if ((png_ptr->row_number & 1) || png_ptr->width < 2)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 6:
if (!(png_ptr->row_number & 1))
{
png_read_finish_row(png_ptr);
return;
}
break;
}
}
#endif
if (!(png_ptr->mode & PNG_HAVE_IDAT))
png_error(png_ptr, "Invalid attempt to read row data");
png_ptr->zstream.next_out = png_ptr->row_buf;
png_ptr->zstream.avail_out =
(uInt)(PNG_ROWBYTES(png_ptr->pixel_depth,
png_ptr->iwidth) + 1);
do
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_crc_finish(png_ptr, 0);
png_ptr->idat_size = png_read_chunk_header(png_ptr);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf,
(png_size_t)png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_error(png_ptr, "Extra compressed data");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression error");
} while (png_ptr->zstream.avail_out);
png_ptr->row_info.color_type = png_ptr->color_type;
png_ptr->row_info.width = png_ptr->iwidth;
png_ptr->row_info.channels = png_ptr->channels;
png_ptr->row_info.bit_depth = png_ptr->bit_depth;
png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
png_ptr->row_info.width);
if (png_ptr->row_buf[0])
png_read_filter_row(png_ptr, &(png_ptr->row_info),
png_ptr->row_buf + 1, png_ptr->prev_row + 1,
(int)(png_ptr->row_buf[0]));
png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
png_ptr->rowbytes + 1);
#ifdef PNG_MNG_FEATURES_SUPPORTED
if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
{
/* Intrapixel differencing */
png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
}
#endif
if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
png_do_read_transformations(png_ptr);
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Blow up interlaced rows to full size */
if (png_ptr->interlaced &&
(png_ptr->transformations & PNG_INTERLACE))
{
if (png_ptr->pass < 6)
/* Old interface (pre-1.0.9):
* png_do_read_interlace(&(png_ptr->row_info),
* png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
*/
png_do_read_interlace(png_ptr);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
if (row != NULL)
png_combine_row(png_ptr, row,
png_pass_mask[png_ptr->pass]);
}
else
#endif
{
if (row != NULL)
png_combine_row(png_ptr, row, 0xff);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row, 0xff);
}
png_read_finish_row(png_ptr);
if (png_ptr->read_row_fn != NULL)
(*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline struct list_head *ptype_head(const struct packet_type *pt)
{
if (pt->type == htons(ETH_P_ALL))
return pt->dev ? &pt->dev->ptype_all : &ptype_all;
else
return pt->dev ? &pt->dev->ptype_specific :
&ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GF_Err stdp_Size(GF_Box *s)
{
GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s;
ptr->size += (2 * ptr->nb_entries);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void mincore_pmd_range(struct vm_area_struct *vma, pud_t *pud,
unsigned long addr, unsigned long end,
unsigned char *vec)
{
unsigned long next;
pmd_t *pmd;
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
if (pmd_trans_huge(*pmd)) {
if (mincore_huge_pmd(vma, pmd, addr, next, vec)) {
vec += (next - addr) >> PAGE_SHIFT;
continue;
}
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
mincore_unmapped_range(vma, addr, next, vec);
else
mincore_pte_range(vma, pmd, addr, next, vec);
vec += (next - addr) >> PAGE_SHIFT;
} while (pmd++, addr = next, addr != end);
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: png_get_progressive_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return (NULL);
return png_ptr->io_ptr;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ptaaWriteStream(FILE *fp,
PTAA *ptaa,
l_int32 type)
{
l_int32 i, n;
PTA *pta;
PROCNAME("ptaaWriteStream");
if (!fp)
return ERROR_INT("stream not defined", procName, 1);
if (!ptaa)
return ERROR_INT("ptaa not defined", procName, 1);
n = ptaaGetCount(ptaa);
fprintf(fp, "\nPtaa Version %d\n", PTA_VERSION_NUMBER);
fprintf(fp, "Number of Pta = %d\n", n);
for (i = 0; i < n; i++) {
pta = ptaaGetPta(ptaa, i, L_CLONE);
ptaWriteStream(fp, pta, type);
ptaDestroy(&pta);
}
return 0;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void runTest()
{
if (m_settings.enableCompositorThread)
CCLayerTreeHostTest::runTest();
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ax25_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
ax25_cb *ax25;
struct net_device *dev;
char devname[IFNAMSIZ];
unsigned long opt;
int res = 0;
if (level != SOL_AX25)
return -ENOPROTOOPT;
if (optlen < sizeof(unsigned int))
return -EINVAL;
if (get_user(opt, (unsigned int __user *)optval))
return -EFAULT;
lock_sock(sk);
ax25 = ax25_sk(sk);
switch (optname) {
case AX25_WINDOW:
if (ax25->modulus == AX25_MODULUS) {
if (opt < 1 || opt > 7) {
res = -EINVAL;
break;
}
} else {
if (opt < 1 || opt > 63) {
res = -EINVAL;
break;
}
}
ax25->window = opt;
break;
case AX25_T1:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->rtt = (opt * HZ) >> 1;
ax25->t1 = opt * HZ;
break;
case AX25_T2:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->t2 = opt * HZ;
break;
case AX25_N2:
if (opt < 1 || opt > 31) {
res = -EINVAL;
break;
}
ax25->n2 = opt;
break;
case AX25_T3:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->t3 = opt * HZ;
break;
case AX25_IDLE:
if (opt > ULONG_MAX / (60 * HZ)) {
res = -EINVAL;
break;
}
ax25->idle = opt * 60 * HZ;
break;
case AX25_BACKOFF:
if (opt > 2) {
res = -EINVAL;
break;
}
ax25->backoff = opt;
break;
case AX25_EXTSEQ:
ax25->modulus = opt ? AX25_EMODULUS : AX25_MODULUS;
break;
case AX25_PIDINCL:
ax25->pidincl = opt ? 1 : 0;
break;
case AX25_IAMDIGI:
ax25->iamdigi = opt ? 1 : 0;
break;
case AX25_PACLEN:
if (opt < 16 || opt > 65535) {
res = -EINVAL;
break;
}
ax25->paclen = opt;
break;
case SO_BINDTODEVICE:
if (optlen > IFNAMSIZ)
optlen = IFNAMSIZ;
if (copy_from_user(devname, optval, optlen)) {
res = -EFAULT;
break;
}
if (sk->sk_type == SOCK_SEQPACKET &&
(sock->state != SS_UNCONNECTED ||
sk->sk_state == TCP_LISTEN)) {
res = -EADDRNOTAVAIL;
break;
}
dev = dev_get_by_name(&init_net, devname);
if (!dev) {
res = -ENODEV;
break;
}
ax25->ax25_dev = ax25_dev_ax25dev(dev);
ax25_fillin_cb(ax25, ax25->ax25_dev);
dev_put(dev);
break;
default:
res = -ENOPROTOOPT;
}
release_sock(sk);
return res;
}
Commit Message: ax25: fix info leak via msg_name in ax25_recvmsg()
When msg_namelen is non-zero the sockaddr info gets filled out, as
requested, but the code fails to initialize the padding bytes of struct
sockaddr_ax25 inserted by the compiler for alignment. Additionally the
msg_namelen value is updated to sizeof(struct full_sockaddr_ax25) but is
not always filled up to this size.
Both issues lead to the fact that the code will leak uninitialized
kernel stack bytes in net/socket.c.
Fix both issues by initializing the memory with memset(0).
Cc: Ralf Baechle <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int PrintPreviewDataService::GetAvailableDraftPageCount(
const std::string& preview_ui_addr_str) {
if (data_store_map_.find(preview_ui_addr_str) != data_store_map_.end())
return data_store_map_[preview_ui_addr_str]->GetAvailableDraftPageCount();
return 0;
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 1
Example 2:
Code: void Notification::close()
{
if (m_state != NotificationStateShowing)
return;
if (m_persistentId == kInvalidPersistentId) {
executionContext()->postTask(BLINK_FROM_HERE, createSameThreadTask(&Notification::dispatchCloseEvent, this));
m_state = NotificationStateClosing;
notificationManager()->close(this);
} else {
m_state = NotificationStateClosed;
SecurityOrigin* origin = executionContext()->securityOrigin();
ASSERT(origin);
notificationManager()->closePersistent(WebSecurityOrigin(origin), m_persistentId);
}
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PluginProcessHost* host() const {
return host_;
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int is_rndis(USBNetState *s)
{
return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE;
}
Commit Message:
CWE ID:
Target: 1
Example 2:
Code: int dns_packet_validate_query(DnsPacket *p) {
int r;
assert(p);
r = dns_packet_validate(p);
if (r < 0)
return r;
if (DNS_PACKET_QR(p) != 0)
return 0;
if (DNS_PACKET_OPCODE(p) != 0)
return -EBADMSG;
if (DNS_PACKET_TC(p))
return -EBADMSG;
switch (p->protocol) {
case DNS_PROTOCOL_LLMNR:
case DNS_PROTOCOL_DNS:
/* RFC 4795, Section 2.1.1. says to discard all queries with QDCOUNT != 1 */
if (DNS_PACKET_QDCOUNT(p) != 1)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with ANCOUNT != 0 */
if (DNS_PACKET_ANCOUNT(p) > 0)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with NSCOUNT != 0 */
if (DNS_PACKET_NSCOUNT(p) > 0)
return -EBADMSG;
break;
case DNS_PROTOCOL_MDNS:
/* RFC 6762, Section 18 */
if (DNS_PACKET_AA(p) != 0 ||
DNS_PACKET_RD(p) != 0 ||
DNS_PACKET_RA(p) != 0 ||
DNS_PACKET_AD(p) != 0 ||
DNS_PACKET_CD(p) != 0 ||
DNS_PACKET_RCODE(p) != 0)
return -EBADMSG;
break;
default:
break;
}
return 1;
}
Commit Message: resolved: bugfix of null pointer p->question dereferencing (#6020)
See https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1621396
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) {
gfx::Point location_in_bar(event->location());
ConvertPointToTarget(this, this->progress_bar_, &location_in_bar);
if (event->type() != ui::ET_GESTURE_TAP ||
!progress_bar_->GetLocalBounds().Contains(location_in_bar)) {
return;
}
HandleSeeking(location_in_bar);
event->SetHandled();
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) {
if (!cl->HasSwitch(switches::kEnableSyncTabs))
cl->AppendSwitch(switches::kEnableSyncTabs);
}
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
Target: 1
Example 2:
Code: int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
struct ext4_ext_path *path)
{
if (path) {
int depth = ext_depth(inode);
int ret = 0;
/* probably there is space in leaf? */
if (le16_to_cpu(path[depth].p_hdr->eh_entries)
< le16_to_cpu(path[depth].p_hdr->eh_max)) {
/*
* There are some space in the leaf tree, no
* need to account for leaf block credit
*
* bitmaps and block group descriptor blocks
* and other metadat blocks still need to be
* accounted.
*/
/* 1 bitmap, 1 block group descriptor */
ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
return ret;
}
}
return ext4_chunk_trans_blocks(inode, nrblocks);
}
Commit Message: ext4: reimplement convert and split_unwritten
Reimplement ext4_ext_convert_to_initialized() and
ext4_split_unwritten_extents() using ext4_split_extent()
Signed-off-by: Yongqiang Yang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Tested-by: Allison Henderson <[email protected]>
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void sas_init_port(struct asd_sas_port *port,
struct sas_ha_struct *sas_ha, int i)
{
memset(port, 0, sizeof(*port));
port->id = i;
INIT_LIST_HEAD(&port->dev_list);
INIT_LIST_HEAD(&port->disco_list);
INIT_LIST_HEAD(&port->destroy_list);
spin_lock_init(&port->phy_list_lock);
INIT_LIST_HEAD(&port->phy_list);
port->ha = sas_ha;
spin_lock_init(&port->dev_list_lock);
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int hashtable_set(hashtable_t *hashtable,
const char *key, size_t serial,
json_t *value)
{
pair_t *pair;
bucket_t *bucket;
size_t hash, index;
/* rehash if the load ratio exceeds 1 */
if(hashtable->size >= num_buckets(hashtable))
if(hashtable_do_rehash(hashtable))
return -1;
hash = hash_str(key);
index = hash % num_buckets(hashtable);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(pair)
{
json_decref(pair->value);
pair->value = value;
}
else
{
/* offsetof(...) returns the size of pair_t without the last,
flexible member. This way, the correct amount is
allocated. */
pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1);
if(!pair)
return -1;
pair->hash = hash;
pair->serial = serial;
strcpy(pair->key, key);
pair->value = value;
list_init(&pair->list);
insert_to_bucket(hashtable, bucket, &pair->list);
hashtable->size++;
}
return 0;
}
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
Target: 1
Example 2:
Code: static int ext4_ext_truncate_extend_restart(handle_t *handle,
struct inode *inode,
int needed)
{
int err;
if (!ext4_handle_valid(handle))
return 0;
if (handle->h_buffer_credits > needed)
return 0;
err = ext4_journal_extend(handle, needed);
if (err <= 0)
return err;
err = ext4_truncate_restart_trans(handle, inode, needed);
/*
* We have dropped i_data_sem so someone might have cached again
* an extent we are going to truncate.
*/
ext4_ext_invalidate_cache(inode);
return err;
}
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 <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AwContents::RequestGeolocationPermission(
const GURL& origin,
const base::Callback<void(bool)>& callback) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
if (Java_AwContents_useLegacyGeolocationPermissionAPI(env, obj.obj())) {
ShowGeolocationPrompt(origin, callback);
return;
}
permission_request_handler_->SendRequest(
scoped_ptr<AwPermissionRequestDelegate>(new SimplePermissionRequest(
origin, AwPermissionRequest::Geolocation, callback)));
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
struct address_space *mapping = inode->i_mapping;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + len - 1);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Now release the pages and zero block aligned part of pages*/
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int will_become_orphaned_pgrp(struct pid *pgrp, struct task_struct *ignored_task)
{
struct task_struct *p;
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
if ((p == ignored_task) ||
(p->exit_state && thread_group_empty(p)) ||
is_global_init(p->real_parent))
continue;
if (task_pgrp(p->real_parent) != pgrp &&
task_session(p->real_parent) == task_session(p))
return 0;
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
return 1;
}
Commit Message: Move "exit_robust_list" into mm_release()
We don't want to get rid of the futexes just at exit() time, we want to
drop them when doing an execve() too, since that gets rid of the
previous VM image too.
Doing it at mm_release() time means that we automatically always do it
when we disassociate a VM map from the task.
Reported-by: [email protected]
Cc: Andrew Morton <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: Alex Efros <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int disarm_req_delay(struct qib_ctxtdata *rcd)
{
int ret = 0;
if (!usable(rcd->ppd)) {
int i;
/*
* if link is down, or otherwise not usable, delay
* the caller up to 30 seconds, so we don't thrash
* in trying to get the chip back to ACTIVE, and
* set flag so they make the call again.
*/
if (rcd->user_event_mask) {
/*
* subctxt_cnt is 0 if not shared, so do base
* separately, first, then remaining subctxt, if any
*/
set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
&rcd->user_event_mask[0]);
for (i = 1; i < rcd->subctxt_cnt; i++)
set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
&rcd->user_event_mask[i]);
}
for (i = 0; !usable(rcd->ppd) && i < 300; i++)
msleep(100);
ret = -ENETDOWN;
}
return ret;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t k90_show_macro_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
const char *macro_mode;
char data[8];
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_GET_MODE,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 2,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial mode (error %d).\n",
ret);
return -EIO;
}
switch (data[0]) {
case K90_MACRO_MODE_HW:
macro_mode = "HW";
break;
case K90_MACRO_MODE_SW:
macro_mode = "SW";
break;
default:
dev_warn(dev, "K90 in unknown mode: %02hhx.\n",
data[0]);
return -EIO;
}
return snprintf(buf, PAGE_SIZE, "%s\n", macro_mode);
}
Commit Message: HID: corsair: fix DMA buffers on stack
Not all platforms support DMA to the stack, and specifically since v4.9
this is no longer supported on x86 with VMAP_STACK either.
Note that the macro-mode buffer was larger than necessary.
Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver")
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ih264d_release_display_bufs(dec_struct_t *ps_dec)
{
WORD32 i, j;
WORD32 i4_min_poc;
WORD32 i4_min_poc_buf_id;
WORD32 i4_min_index;
dpb_manager_t *ps_dpb_mgr = ps_dec->ps_dpb_mgr;
WORD32 (*i4_poc_buf_id_map)[3] = ps_dpb_mgr->ai4_poc_buf_id_map;
i4_min_poc = 0x7fffffff;
i4_min_poc_buf_id = -1;
i4_min_index = -1;
ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr);
for(j = 0; j < ps_dpb_mgr->i1_poc_buf_id_entries; j++)
{
i4_min_poc = 0x7fffffff;
for(i = 0; i < MAX_FRAMES; i++)
{
if(i4_poc_buf_id_map[i][0] != -1)
{
if(i4_poc_buf_id_map[i][1] < i4_min_poc)
{
i4_min_poc = i4_poc_buf_id_map[i][1];
i4_min_poc_buf_id = i4_poc_buf_id_map[i][0];
i4_min_index = i;
}
}
}
if(DO_NOT_DISP != i4_min_poc_buf_id)
{
ps_dec->i4_cur_display_seq++;
ih264_disp_mgr_add(
(disp_mgr_t *)ps_dec->pv_disp_buf_mgr,
i4_min_poc_buf_id, ps_dec->i4_cur_display_seq,
ps_dec->apv_buf_id_pic_buf_map[i4_min_poc_buf_id]);
i4_poc_buf_id_map[i4_min_index][0] = -1;
i4_poc_buf_id_map[i4_min_index][1] = 0x7fffffff;
ps_dpb_mgr->ai4_poc_buf_id_map[i4_min_index][2] = 0;
}
else
{
i4_poc_buf_id_map[i4_min_index][0] = -1;
i4_poc_buf_id_map[i4_min_index][1] = 0x7fffffff;
ps_dpb_mgr->ai4_poc_buf_id_map[i4_min_index][2] = 0;
}
}
ps_dpb_mgr->i1_poc_buf_id_entries = 0;
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering
+ 1;
ps_dec->i4_max_poc = 0;
}
Commit Message: Decoder: Fixed error handling for dangling fields
In case of dangling fields with gaps in frames enabled,
field pic in cur_slice was wrongly set to 0.
This would cause dangling field to be concealed as a frame, which would
result in a number of MB mismatch and hence a hang.
Bug: 34097672
Change-Id: Ia9b7f72c4676188c45790b2dfbb4fe2c2d2c01f8
(cherry picked from commit 1a13168ca3510ba91274d10fdee46b3642cc9554)
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static jobject android_net_wifi_getLinkLayerStats (JNIEnv *env, jclass cls, jint iface) {
JNIHelper helper(env);
wifi_stats_result_handler handler;
memset(&handler, 0, sizeof(handler));
handler.on_link_stats_results = &onLinkStatsResults;
wifi_interface_handle handle = getIfaceHandle(helper, cls, iface);
int result = hal_fn.wifi_get_link_stats(0, handle, handler);
if (result < 0) {
ALOGE("android_net_wifi_getLinkLayerStats: failed to get link statistics\n");
return NULL;
}
JNIObject<jobject> wifiLinkLayerStats = helper.createObject(
"android/net/wifi/WifiLinkLayerStats");
if (wifiLinkLayerStats == NULL) {
ALOGE("Error in allocating wifiLinkLayerStats");
return NULL;
}
helper.setIntField(wifiLinkLayerStats, "beacon_rx", link_stat.beacon_rx);
helper.setIntField(wifiLinkLayerStats, "rssi_mgmt", link_stat.rssi_mgmt);
helper.setLongField(wifiLinkLayerStats, "rxmpdu_be", link_stat.ac[WIFI_AC_BE].rx_mpdu);
helper.setLongField(wifiLinkLayerStats, "rxmpdu_bk", link_stat.ac[WIFI_AC_BK].rx_mpdu);
helper.setLongField(wifiLinkLayerStats, "rxmpdu_vi", link_stat.ac[WIFI_AC_VI].rx_mpdu);
helper.setLongField(wifiLinkLayerStats, "rxmpdu_vo", link_stat.ac[WIFI_AC_VO].rx_mpdu);
helper.setLongField(wifiLinkLayerStats, "txmpdu_be", link_stat.ac[WIFI_AC_BE].tx_mpdu);
helper.setLongField(wifiLinkLayerStats, "txmpdu_bk", link_stat.ac[WIFI_AC_BK].tx_mpdu);
helper.setLongField(wifiLinkLayerStats, "txmpdu_vi", link_stat.ac[WIFI_AC_VI].tx_mpdu);
helper.setLongField(wifiLinkLayerStats, "txmpdu_vo", link_stat.ac[WIFI_AC_VO].tx_mpdu);
helper.setLongField(wifiLinkLayerStats, "lostmpdu_be", link_stat.ac[WIFI_AC_BE].mpdu_lost);
helper.setLongField(wifiLinkLayerStats, "lostmpdu_bk", link_stat.ac[WIFI_AC_BK].mpdu_lost);
helper.setLongField(wifiLinkLayerStats, "lostmpdu_vi", link_stat.ac[WIFI_AC_VI].mpdu_lost);
helper.setLongField(wifiLinkLayerStats, "lostmpdu_vo", link_stat.ac[WIFI_AC_VO].mpdu_lost);
helper.setLongField(wifiLinkLayerStats, "retries_be", link_stat.ac[WIFI_AC_BE].retries);
helper.setLongField(wifiLinkLayerStats, "retries_bk", link_stat.ac[WIFI_AC_BK].retries);
helper.setLongField(wifiLinkLayerStats, "retries_vi", link_stat.ac[WIFI_AC_VI].retries);
helper.setLongField(wifiLinkLayerStats, "retries_vo", link_stat.ac[WIFI_AC_VO].retries);
helper.setIntField(wifiLinkLayerStats, "on_time", radio_stat.on_time);
helper.setIntField(wifiLinkLayerStats, "tx_time", radio_stat.tx_time);
helper.setIntField(wifiLinkLayerStats, "rx_time", radio_stat.rx_time);
helper.setIntField(wifiLinkLayerStats, "on_time_scan", radio_stat.on_time_scan);
return wifiLinkLayerStats.detach();
}
Commit Message: Deal correctly with short strings
The parseMacAddress function anticipates only properly formed
MAC addresses (6 hexadecimal octets separated by ":"). This
change properly deals with situations where the string is
shorter than expected, making sure that the passed in char*
reference in parseHexByte never exceeds the end of the string.
BUG: 28164077
TEST: Added a main function:
int main(int argc, char **argv) {
unsigned char addr[6];
if (argc > 1) {
memset(addr, 0, sizeof(addr));
parseMacAddress(argv[1], addr);
printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
}
}
Tested with "", "a" "ab" "ab:c" "abxc".
Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void MediaStreamDispatcherHost::CancelRequest(int page_request_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->CancelRequest(render_process_id_, render_frame_id_,
page_request_id);
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void disk_flush_events(struct gendisk *disk, unsigned int mask)
{
struct disk_events *ev = disk->ev;
if (!ev)
return;
spin_lock_irq(&ev->lock);
ev->clearing |= mask;
if (!ev->block)
mod_delayed_work(system_freezable_power_efficient_wq,
&ev->dwork, 0);
spin_unlock_irq(&ev->lock);
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DesktopWindowTreeHostX11::Restore() {
should_maximize_after_map_ = false;
SetWMSpecState(false, gfx::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"),
gfx::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ"));
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
SetWMSpecState(false, gfx::GetAtom("_NET_WM_STATE_HIDDEN"), x11::None);
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Cluster::GetLast(const BlockEntry*& pLast) const
{
for (;;)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pLast = NULL;
return status;
}
if (status > 0) //no new block
break;
}
if (m_entries_count <= 0)
{
pLast = NULL;
return 0;
}
assert(m_entries);
const long idx = m_entries_count - 1;
pLast = m_entries[idx];
assert(pLast);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: void credssp_read_ts_password_creds(rdpCredssp* credssp, wStream* s)
{
int length;
/* TSPasswordCreds (SEQUENCE) */
ber_read_sequence_tag(s, &length);
/* [0] domainName (OCTET STRING) */
ber_read_contextual_tag(s, 0, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.DomainLength = (UINT32) length;
credssp->identity.Domain = (UINT16*) malloc(length);
CopyMemory(credssp->identity.Domain, Stream_Pointer(s), credssp->identity.DomainLength);
Stream_Seek(s, credssp->identity.DomainLength);
credssp->identity.DomainLength /= 2;
/* [1] userName (OCTET STRING) */
ber_read_contextual_tag(s, 1, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.UserLength = (UINT32) length;
credssp->identity.User = (UINT16*) malloc(length);
CopyMemory(credssp->identity.User, Stream_Pointer(s), credssp->identity.UserLength);
Stream_Seek(s, credssp->identity.UserLength);
credssp->identity.UserLength /= 2;
/* [2] password (OCTET STRING) */
ber_read_contextual_tag(s, 2, &length, TRUE);
ber_read_octet_string_tag(s, &length);
credssp->identity.PasswordLength = (UINT32) length;
credssp->identity.Password = (UINT16*) malloc(length);
CopyMemory(credssp->identity.Password, Stream_Pointer(s), credssp->identity.PasswordLength);
Stream_Seek(s, credssp->identity.PasswordLength);
credssp->identity.PasswordLength /= 2;
credssp->identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void TearDown() {
libvpx_test::ClearSystemState();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
{
setDeviceOrientationOverride(error, 0, 0, 0);
}
Commit Message: DevTools: remove references to modules/device_orientation from core
BUG=340221
Review URL: https://codereview.chromium.org/150913003
git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: RTCVoidRequestImpl::RTCVoidRequestImpl(ScriptExecutionContext* context, PassRefPtr<VoidCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback)
: ActiveDOMObject(context, this)
, m_successCallback(successCallback)
, m_errorCallback(errorCallback)
{
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int av_codec_is_decoder(const AVCodec *codec)
{
return codec && (codec->decode || codec->receive_frame);
}
Commit Message: avcodec/utils: Check close before calling it
Fixes: NULL pointer dereference
Fixes: 15733/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_IDF_fuzzer-5658616977162240
Reviewed-by: Paul B Mahol <[email protected]>
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ext4_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = d_inode(dentry);
int error, rc = 0;
int orphan = 0;
const unsigned int ia_valid = attr->ia_valid;
error = inode_change_ok(inode, attr);
if (error)
return error;
if (is_quota_modification(inode, attr)) {
error = dquot_initialize(inode);
if (error)
return error;
}
if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
(ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
handle_t *handle;
/* (user+group)*(old+new) structure, inode write (sb,
* inode block, ? - but truncate inode update has it) */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto err_out;
}
error = dquot_transfer(inode, attr);
if (error) {
ext4_journal_stop(handle);
return error;
}
/* Update corresponding info in inode so that everything is in
* one transaction */
if (attr->ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (attr->ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
error = ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
}
if (attr->ia_valid & ATTR_SIZE) {
handle_t *handle;
loff_t oldsize = inode->i_size;
int shrink = (attr->ia_size <= inode->i_size);
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (attr->ia_size > sbi->s_bitmap_maxbytes)
return -EFBIG;
}
if (!S_ISREG(inode->i_mode))
return -EINVAL;
if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
inode_inc_iversion(inode);
if (ext4_should_order_data(inode) &&
(attr->ia_size < inode->i_size)) {
error = ext4_begin_ordered_truncate(inode,
attr->ia_size);
if (error)
goto err_out;
}
if (attr->ia_size != inode->i_size) {
handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto err_out;
}
if (ext4_handle_valid(handle) && shrink) {
error = ext4_orphan_add(handle, inode);
orphan = 1;
}
/*
* Update c/mtime on truncate up, ext4_truncate() will
* update c/mtime in shrink case below
*/
if (!shrink) {
inode->i_mtime = ext4_current_time(inode);
inode->i_ctime = inode->i_mtime;
}
down_write(&EXT4_I(inode)->i_data_sem);
EXT4_I(inode)->i_disksize = attr->ia_size;
rc = ext4_mark_inode_dirty(handle, inode);
if (!error)
error = rc;
/*
* We have to update i_size under i_data_sem together
* with i_disksize to avoid races with writeback code
* running ext4_wb_update_i_disksize().
*/
if (!error)
i_size_write(inode, attr->ia_size);
up_write(&EXT4_I(inode)->i_data_sem);
ext4_journal_stop(handle);
if (error) {
if (orphan)
ext4_orphan_del(NULL, inode);
goto err_out;
}
}
if (!shrink)
pagecache_isize_extended(inode, oldsize, inode->i_size);
/*
* Blocks are going to be removed from the inode. Wait
* for dio in flight. Temporarily disable
* dioread_nolock to prevent livelock.
*/
if (orphan) {
if (!ext4_should_journal_data(inode)) {
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ext4_inode_resume_unlocked_dio(inode);
} else
ext4_wait_for_tail_page_commit(inode);
}
/*
* Truncate pagecache after we've waited for commit
* in data=journal mode to make pages freeable.
*/
truncate_pagecache(inode, inode->i_size);
if (shrink)
ext4_truncate(inode);
}
if (!rc) {
setattr_copy(inode, attr);
mark_inode_dirty(inode);
}
/*
* If the call to ext4_truncate failed to get a transaction handle at
* all, we need to clean up the in-core orphan list manually.
*/
if (orphan && inode->i_nlink)
ext4_orphan_del(NULL, inode);
if (!rc && (ia_valid & ATTR_MODE))
rc = posix_acl_chmod(inode, inode->i_mode);
err_out:
ext4_std_error(inode->i_sb, error);
if (!error)
error = rc;
return error;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: gfx::NativePixmapHandle>::Read(gfx::mojom::NativePixmapHandleDataView data,
gfx::NativePixmapHandle* out) {
#if defined(OS_LINUX)
mojo::ArrayDataView<mojo::ScopedHandle> handles_data_view;
data.GetFdsDataView(&handles_data_view);
for (size_t i = 0; i < handles_data_view.size(); ++i) {
mojo::ScopedHandle handle = handles_data_view.Take(i);
base::PlatformFile platform_file;
if (mojo::UnwrapPlatformFile(std::move(handle), &platform_file) !=
MOJO_RESULT_OK)
return false;
constexpr bool auto_close = true;
out->fds.push_back(base::FileDescriptor(platform_file, auto_close));
}
return data.ReadPlanes(&out->planes);
#else
return false;
#endif
}
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 <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, open_flags);
write_sequnlock(&state->seqlock);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: ofputil_count_ipfix_stats(const struct ofp_header *oh)
{
struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
ofpraw_pull_assert(&b);
return b.size / sizeof(struct ofputil_ipfix_stats);
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLOutputSurfaceBufferQueueAndroid::HandlePartialSwap(
const gfx::Rect& sub_buffer_rect,
uint32_t flags,
gpu::ContextSupport::SwapCompletedCallback swap_callback,
gpu::ContextSupport::PresentationCallback presentation_callback) {
DCHECK(sub_buffer_rect.IsEmpty());
context_provider_->ContextSupport()->CommitOverlayPlanes(
flags, std::move(swap_callback), std::move(presentation_callback));
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BOOL png2pnm (FILE *png_file, FILE *pnm_file, FILE *alpha_file, BOOL raw, BOOL alpha)
{
png_struct *png_ptr = NULL;
png_info *info_ptr = NULL;
png_byte buf[8];
png_byte *png_pixels = NULL;
png_byte **row_pointers = NULL;
png_byte *pix_ptr = NULL;
png_uint_32 row_bytes;
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int channels;
int color_type;
int alpha_present;
int row, col;
int ret;
int i;
long dep_16;
/* read and check signature in PNG file */
ret = fread (buf, 1, 8, png_file);
if (ret != 8)
return FALSE;
ret = png_sig_cmp (buf, 0, 8);
if (ret)
return FALSE;
/* create png and info structures */
png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if (!png_ptr)
return FALSE; /* out of memory */
info_ptr = png_create_info_struct (png_ptr);
if (!info_ptr)
{
png_destroy_read_struct (&png_ptr, NULL, NULL);
return FALSE; /* out of memory */
}
if (setjmp (png_jmpbuf(png_ptr)))
{
png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
return FALSE;
}
/* set up the input control for C streams */
png_init_io (png_ptr, png_file);
png_set_sig_bytes (png_ptr, 8); /* we already read the 8 signature bytes */
/* read the file information */
png_read_info (png_ptr, info_ptr);
/* get size and bit-depth of the PNG-image */
png_get_IHDR (png_ptr, info_ptr,
&width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
/* set-up the transformations */
/* transform paletted images into full-color rgb */
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_expand (png_ptr);
/* expand images to bit-depth 8 (only applicable for grayscale images) */
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand (png_ptr);
/* transform transparency maps into full alpha-channel */
if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_expand (png_ptr);
#ifdef NJET
/* downgrade 16-bit images to 8 bit */
if (bit_depth == 16)
png_set_strip_16 (png_ptr);
/* transform grayscale images into full-color */
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb (png_ptr);
/* only if file has a file gamma, we do a correction */
if (png_get_gAMA (png_ptr, info_ptr, &file_gamma))
png_set_gamma (png_ptr, (double) 2.2, file_gamma);
#endif
/* all transformations have been registered; now update info_ptr data,
* get rowbytes and channels, and allocate image memory */
png_read_update_info (png_ptr, info_ptr);
/* get the new color-type and bit-depth (after expansion/stripping) */
png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
/* check for 16-bit files */
if (bit_depth == 16)
{
raw = FALSE;
#ifdef __TURBOC__
pnm_file->flags &= ~((unsigned) _F_BIN);
#endif
}
/* calculate new number of channels and store alpha-presence */
if (color_type == PNG_COLOR_TYPE_GRAY)
channels = 1;
else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
channels = 2;
else if (color_type == PNG_COLOR_TYPE_RGB)
channels = 3;
else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
channels = 4;
else
channels = 0; /* should never happen */
alpha_present = (channels - 1) % 2;
/* check if alpha is expected to be present in file */
if (alpha && !alpha_present)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: PNG-file doesn't contain alpha channel\n");
exit (1);
}
/* row_bytes is the width x number of channels x (bit-depth / 8) */
row_bytes = png_get_rowbytes (png_ptr, info_ptr);
if ((png_pixels = (png_byte *) malloc (row_bytes * height * sizeof (png_byte))) == NULL) {
png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
return FALSE;
}
if ((row_pointers = (png_byte **) malloc (height * sizeof (png_bytep))) == NULL)
{
png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
free (png_pixels);
png_pixels = NULL;
return FALSE;
}
/* set the individual row_pointers to point at the correct offsets */
for (i = 0; i < (height); i++)
row_pointers[i] = png_pixels + i * row_bytes;
/* now we can go ahead and just read the whole image */
png_read_image (png_ptr, row_pointers);
/* read rest of file, and get additional chunks in info_ptr - REQUIRED */
png_read_end (png_ptr, info_ptr);
/* clean up after the read, and free any memory allocated - REQUIRED */
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp) NULL);
/* write header of PNM file */
if ((color_type == PNG_COLOR_TYPE_GRAY) ||
(color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
fprintf (pnm_file, "%s\n", (raw) ? "P5" : "P2");
fprintf (pnm_file, "%d %d\n", (int) width, (int) height);
fprintf (pnm_file, "%ld\n", ((1L << (int) bit_depth) - 1L));
}
else if ((color_type == PNG_COLOR_TYPE_RGB) ||
(color_type == PNG_COLOR_TYPE_RGB_ALPHA))
{
fprintf (pnm_file, "%s\n", (raw) ? "P6" : "P3");
fprintf (pnm_file, "%d %d\n", (int) width, (int) height);
fprintf (pnm_file, "%ld\n", ((1L << (int) bit_depth) - 1L));
}
/* write header of PGM file with alpha channel */
if ((alpha) &&
((color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
{
fprintf (alpha_file, "%s\n", (raw) ? "P5" : "P2");
fprintf (alpha_file, "%d %d\n", (int) width, (int) height);
fprintf (alpha_file, "%ld\n", ((1L << (int) bit_depth) - 1L));
}
/* write data to PNM file */
pix_ptr = png_pixels;
for (row = 0; row < height; row++)
{
for (col = 0; col < width; col++)
{
for (i = 0; i < (channels - alpha_present); i++)
{
if (raw)
fputc ((int) *pix_ptr++ , pnm_file);
else
if (bit_depth == 16){
dep_16 = (long) *pix_ptr++;
fprintf (pnm_file, "%ld ", (dep_16 << 8) + ((long) *pix_ptr++));
}
else
fprintf (pnm_file, "%ld ", (long) *pix_ptr++);
}
if (alpha_present)
{
if (!alpha)
{
pix_ptr++; /* alpha */
if (bit_depth == 16)
pix_ptr++;
}
else /* output alpha-channel as pgm file */
{
if (raw)
fputc ((int) *pix_ptr++ , alpha_file);
else
if (bit_depth == 16){
dep_16 = (long) *pix_ptr++;
fprintf (alpha_file, "%ld ", (dep_16 << 8) + (long) *pix_ptr++);
}
else
fprintf (alpha_file, "%ld ", (long) *pix_ptr++);
}
} /* if alpha_present */
if (!raw)
if (col % 4 == 3)
fprintf (pnm_file, "\n");
} /* end for col */
if (!raw)
if (col % 4 != 0)
fprintf (pnm_file, "\n");
} /* end for row */
if (row_pointers != (unsigned char**) NULL)
free (row_pointers);
if (png_pixels != (unsigned char*) NULL)
free (png_pixels);
return TRUE;
} /* end of source */
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: static void setterRaisesExceptionLongAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
TestObjectPythonV8Internal::setterRaisesExceptionLongAttributeAttributeSetter(jsValue, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
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
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned int task_scan_start(struct task_struct *p)
{
unsigned long smin = task_scan_min(p);
unsigned long period = smin;
/* Scale the maximum scan period with the amount of shared memory. */
if (p->numa_group) {
struct numa_group *ng = p->numa_group;
unsigned long shared = group_faults_shared(ng);
unsigned long private = group_faults_priv(ng);
period *= atomic_read(&ng->refcount);
period *= shared + 1;
period /= private + shared + 1;
}
return max(smin, period);
}
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt)
{
struct serial_icounter_struct icount;
struct sb_uart_icount cnow;
struct sb_uart_port *port = state->port;
spin_lock_irq(&port->lock);
memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));
spin_unlock_irq(&port->lock);
icount.cts = cnow.cts;
icount.dsr = cnow.dsr;
icount.rng = cnow.rng;
icount.dcd = cnow.dcd;
icount.rx = cnow.rx;
icount.tx = cnow.tx;
icount.frame = cnow.frame;
icount.overrun = cnow.overrun;
icount.parity = cnow.parity;
icount.brk = cnow.brk;
icount.buf_overrun = cnow.buf_overrun;
return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0;
}
Commit Message: Staging: sb105x: info leak in mp_get_count()
The icount.reserved[] array isn't initialized so it leaks stack
information to userspace.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void propagate_entity_cfs_rq(struct sched_entity *se) { }
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) {
int dummy;
Bool pixmaps_supported;
if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported))
return SHARED_MEMORY_NONE;
#if defined(OS_FREEBSD)
int allow_removed;
size_t length = sizeof(allow_removed);
if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length,
NULL, 0) < 0) || allow_removed < 1) {
return SHARED_MEMORY_NONE;
}
#endif
int shmkey = shmget(IPC_PRIVATE, 1, 0666);
if (shmkey == -1)
return SHARED_MEMORY_NONE;
void* address = shmat(shmkey, NULL, 0);
shmctl(shmkey, IPC_RMID, NULL);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shmkey;
gdk_error_trap_push();
bool result = XShmAttach(dpy, &shminfo);
XSync(dpy, False);
if (gdk_error_trap_pop())
result = false;
shmdt(address);
if (!result)
return SHARED_MEMORY_NONE;
XShmDetach(dpy, &shminfo);
return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() {
InputMethodDescriptors* descriptors = new InputMethodDescriptors;
descriptors->push_back(
input_method::GetFallbackInputMethodDescriptor());
return descriptors;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: cwd_is_root (char const *name)
{
unsigned int prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
char root[prefix_len + 2];
struct stat st;
dev_t root_dev;
ino_t root_ino;
memcpy (root, name, prefix_len);
root[prefix_len] = '/';
root[prefix_len + 1] = 0;
if (stat (root, &st))
return false;
root_dev = st.st_dev;
root_ino = st.st_ino;
if (stat (".", &st))
return false;
return root_dev == st.st_dev && root_ino == st.st_ino;
}
Commit Message:
CWE ID: CWE-59
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId,
wStream* s)
{
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp,
cbChId,
ChannelId);
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void registerRewriteURL(const char* fromURL, const char* toURL)
{
m_rewriteURLs.add(fromURL, toURL);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: explicit TestServiceImpl() {}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <[email protected]>
Commit-Queue: John Abd-El-Malek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void find_entity_for_char(
unsigned int k,
enum entity_charset charset,
const entity_stage1_row *table,
const unsigned char **entity,
size_t *entity_len,
unsigned char *old,
size_t oldlen,
size_t *cursor)
{
unsigned stage1_idx = ENT_STAGE1_INDEX(k);
const entity_stage3_row *c;
if (stage1_idx > 0x1D) {
*entity = NULL;
*entity_len = 0;
return;
}
c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
if (!c->ambiguous) {
*entity = (const unsigned char *)c->data.ent.entity;
*entity_len = c->data.ent.entity_len;
} else {
/* peek at next char */
size_t cursor_before = *cursor;
int status = SUCCESS;
unsigned next_char;
if (!(*cursor < oldlen))
goto no_suitable_2nd;
next_char = get_next_char(charset, old, oldlen, cursor, &status);
if (status == FAILURE)
goto no_suitable_2nd;
{
const entity_multicodepoint_row *s, *e;
s = &c->data.multicodepoint_table[1];
e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
/* we could do a binary search but it's not worth it since we have
* at most two entries... */
for ( ; s <= e; s++) {
if (s->normal_entry.second_cp == next_char) {
*entity = s->normal_entry.entity;
*entity_len = s->normal_entry.entity_len;
return;
}
}
}
no_suitable_2nd:
*cursor = cursor_before;
*entity = (const unsigned char *)
c->data.multicodepoint_table[0].leading_entry.default_entity;
*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
{
struct session_state *state = ssh->state;
u_int padlen, need;
u_char *cp;
u_int maclen, aadlen = 0, authlen = 0, block_size;
struct sshenc *enc = NULL;
struct sshmac *mac = NULL;
struct sshcomp *comp = NULL;
int r;
*typep = SSH_MSG_NONE;
if (state->packet_discard)
return 0;
if (state->newkeys[MODE_IN] != NULL) {
enc = &state->newkeys[MODE_IN]->enc;
mac = &state->newkeys[MODE_IN]->mac;
comp = &state->newkeys[MODE_IN]->comp;
/* disable mac for authenticated encryption */
if ((authlen = cipher_authlen(enc->cipher)) != 0)
mac = NULL;
}
maclen = mac && mac->enabled ? mac->mac_len : 0;
block_size = enc ? enc->block_size : 8;
aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
if (aadlen && state->packlen == 0) {
if (cipher_get_length(state->receive_context,
&state->packlen, state->p_read.seqnr,
sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
return 0;
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
sshbuf_dump(state->input, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
sshbuf_reset(state->incoming_packet);
} else if (state->packlen == 0) {
/*
* check if input size is less than the cipher block size,
* decrypt first block and extract length of incoming packet
*/
if (sshbuf_len(state->input) < block_size)
return 0;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_reserve(state->incoming_packet, block_size,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context,
state->p_send.seqnr, cp, sshbuf_ptr(state->input),
block_size, 0, 0)) != 0)
goto out;
state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
if (state->packlen < 1 + 4 ||
state->packlen > PACKET_MAX_SIZE) {
#ifdef PACKET_DEBUG
fprintf(stderr, "input: \n");
sshbuf_dump(state->input, stderr);
fprintf(stderr, "incoming_packet: \n");
sshbuf_dump(state->incoming_packet, stderr);
#endif
logit("Bad packet length %u.", state->packlen);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE);
}
if ((r = sshbuf_consume(state->input, block_size)) != 0)
goto out;
}
DBG(debug("input: packet len %u", state->packlen+4));
if (aadlen) {
/* only the payload is encrypted */
need = state->packlen;
} else {
/*
* the payload size and the payload are encrypted, but we
* have a partial packet of block_size bytes
*/
need = 4 + state->packlen - block_size;
}
DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
" aadlen %d", block_size, need, maclen, authlen, aadlen));
if (need % block_size != 0) {
logit("padding error: need %d block %d mod %d",
need, block_size, need % block_size);
return ssh_packet_start_discard(ssh, enc, mac, 0,
PACKET_MAX_SIZE - block_size);
}
/*
* check if the entire packet has been received and
* decrypt into incoming_packet:
* 'aadlen' bytes are unencrypted, but authenticated.
* 'need' bytes are encrypted, followed by either
* 'authlen' bytes of authentication tag or
* 'maclen' bytes of message authentication code.
*/
if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
return 0; /* packet is incomplete */
#ifdef PACKET_DEBUG
fprintf(stderr, "read_poll enc/full: ");
sshbuf_dump(state->input, stderr);
#endif
/* EtM: check mac over encrypted input */
if (mac && mac->enabled && mac->etm) {
if ((r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->input), aadlen + need,
sshbuf_ptr(state->input) + aadlen + need + authlen,
maclen)) != 0) {
if (r == SSH_ERR_MAC_INVALID)
logit("Corrupted MAC on input.");
goto out;
}
}
if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
&cp)) != 0)
goto out;
if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
goto out;
if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
goto out;
if (mac && mac->enabled) {
/* Not EtM: check MAC over cleartext */
if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
sshbuf_ptr(state->incoming_packet),
sshbuf_len(state->incoming_packet),
sshbuf_ptr(state->input), maclen)) != 0) {
if (r != SSH_ERR_MAC_INVALID)
goto out;
logit("Corrupted MAC on input.");
if (need > PACKET_MAX_SIZE)
return SSH_ERR_INTERNAL_ERROR;
return ssh_packet_start_discard(ssh, enc, mac,
sshbuf_len(state->incoming_packet),
PACKET_MAX_SIZE - need);
}
/* Remove MAC from input buffer */
DBG(debug("MAC #%d ok", state->p_read.seqnr));
if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
goto out;
}
if (seqnr_p != NULL)
*seqnr_p = state->p_read.seqnr;
if (++state->p_read.seqnr == 0)
logit("incoming seqnr wraps around");
if (++state->p_read.packets == 0)
if (!(ssh->compat & SSH_BUG_NOREKEY))
return SSH_ERR_NEED_REKEY;
state->p_read.blocks += (state->packlen + 4) / block_size;
state->p_read.bytes += state->packlen + 4;
/* get padlen */
padlen = sshbuf_ptr(state->incoming_packet)[4];
DBG(debug("input: padlen %d", padlen));
if (padlen < 4) {
if ((r = sshpkt_disconnect(ssh,
"Corrupted padlen %d on input.", padlen)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_CONN_CORRUPT;
}
/* skip packet size + padlen, discard padding */
if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
goto out;
DBG(debug("input: len before de-compress %zd",
sshbuf_len(state->incoming_packet)));
if (comp && comp->enabled) {
sshbuf_reset(state->compression_buffer);
if ((r = uncompress_buffer(ssh, state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
sshbuf_reset(state->incoming_packet);
if ((r = sshbuf_putb(state->incoming_packet,
state->compression_buffer)) != 0)
goto out;
DBG(debug("input: len after de-compress %zd",
sshbuf_len(state->incoming_packet)));
}
/*
* get packet type, implies consume.
* return length of payload (without type field)
*/
if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
goto out;
if (ssh_packet_log_type(*typep))
debug3("receive packet: type %u", *typep);
if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
if ((r = sshpkt_disconnect(ssh,
"Invalid ssh2 packet type: %d", *typep)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
return r;
return SSH_ERR_PROTOCOL_ERROR;
}
if (*typep == SSH2_MSG_NEWKEYS)
r = ssh_set_newkeys(ssh, MODE_IN);
else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
r = ssh_packet_enable_delayed_compress(ssh);
else
r = 0;
else
r = 0;
#ifdef PACKET_DEBUG
fprintf(stderr, "read/plain[%d]:\r\n", *typep);
sshbuf_dump(state->incoming_packet, stderr);
#endif
/* reset for next packet */
state->packlen = 0;
/* do we need to rekey? */
if (ssh_packet_need_rekeying(ssh, 0)) {
debug3("%s: rekex triggered", __func__);
if ((r = kex_start_rekex(ssh)) != 0)
return r;
}
out:
return r;
}
Commit Message:
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int cdrom_get_random_writable(struct cdrom_device_info *cdi,
struct rwrt_feature_desc *rfd)
{
struct packet_command cgc;
char buffer[24];
int ret;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
cgc.cmd[0] = GPCMD_GET_CONFIGURATION; /* often 0x46 */
cgc.cmd[3] = CDF_RWRT; /* often 0x0020 */
cgc.cmd[8] = sizeof(buffer); /* often 0x18 */
cgc.quiet = 1;
if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
return ret;
memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));
return 0;
}
Commit Message: cdrom: fix improper type cast, which can leat to information leak.
There is another cast from unsigned long to int which causes
a bounds check to fail with specially crafted input. The value is
then used as an index in the slot array in cdrom_slot_status().
This issue is similar to CVE-2018-16658 and CVE-2018-10940.
Signed-off-by: Young_X <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int vol_effect_command(effect_handle_t self,
uint32_t cmd_code, uint32_t cmd_size,
void *p_cmd_data, uint32_t *reply_size,
void *p_reply_data)
{
vol_listener_context_t *context = (vol_listener_context_t *)self;
int status = 0;
ALOGV("%s Called ", __func__);
pthread_mutex_lock(&vol_listner_init_lock);
if (context == NULL || context->state == VOL_LISTENER_STATE_UNINITIALIZED) {
ALOGE("%s: %s is NULL", __func__, (context == NULL) ?
"context" : "context->state");
status = -EINVAL;
goto exit;
}
switch (cmd_code) {
case EFFECT_CMD_INIT:
ALOGV("%s :: cmd called EFFECT_CMD_INIT", __func__);
if (p_reply_data == NULL || *reply_size != sizeof(int)) {
ALOGE("%s: EFFECT_CMD_INIT: %s, sending -EINVAL", __func__,
(p_reply_data == NULL) ? "p_reply_data is NULL" :
"*reply_size != sizeof(int)");
return -EINVAL;
}
*(int *)p_reply_data = 0;
break;
case EFFECT_CMD_SET_CONFIG:
ALOGV("%s :: cmd called EFFECT_CMD_SET_CONFIG", __func__);
break;
case EFFECT_CMD_GET_CONFIG:
ALOGV("%s :: cmd called EFFECT_CMD_GET_CONFIG", __func__);
break;
case EFFECT_CMD_RESET:
ALOGV("%s :: cmd called EFFECT_CMD_RESET", __func__);
break;
case EFFECT_CMD_SET_AUDIO_MODE:
ALOGV("%s :: cmd called EFFECT_CMD_SET_AUDIO_MODE", __func__);
break;
case EFFECT_CMD_OFFLOAD:
ALOGV("%s :: cmd called EFFECT_CMD_OFFLOAD", __func__);
if (p_reply_data == NULL || *reply_size != sizeof(int)) {
ALOGE("%s: EFFECT_CMD_OFFLOAD: %s, sending -EINVAL", __func__,
(p_reply_data == NULL) ? "p_reply_data is NULL" :
"*reply_size != sizeof(int)");
return -EINVAL;
}
*(int *)p_reply_data = 0;
break;
case EFFECT_CMD_ENABLE:
ALOGV("%s :: cmd called EFFECT_CMD_ENABLE", __func__);
if (p_reply_data == NULL || *reply_size != sizeof(int)) {
ALOGE("%s: EFFECT_CMD_ENABLE: %s, sending -EINVAL", __func__,
(p_reply_data == NULL) ? "p_reply_data is NULL" :
"*reply_size != sizeof(int)");
status = -EINVAL;
goto exit;
}
if (context->state != VOL_LISTENER_STATE_INITIALIZED) {
ALOGE("%s: EFFECT_CMD_ENABLE : state not INITIALIZED", __func__);
status = -ENOSYS;
goto exit;
}
context->state = VOL_LISTENER_STATE_ACTIVE;
*(int *)p_reply_data = 0;
if (context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) {
check_and_set_gain_dep_cal();
}
break;
case EFFECT_CMD_DISABLE:
ALOGV("%s :: cmd called EFFECT_CMD_DISABLE", __func__);
if (p_reply_data == NULL || *reply_size != sizeof(int)) {
ALOGE("%s: EFFECT_CMD_DISABLE: %s, sending -EINVAL", __func__,
(p_reply_data == NULL) ? "p_reply_data is NULL" :
"*reply_size != sizeof(int)");
status = -EINVAL;
goto exit;
}
if (context->state != VOL_LISTENER_STATE_ACTIVE) {
ALOGE("%s: EFFECT_CMD_ENABLE : state not ACTIVE", __func__);
status = -ENOSYS;
goto exit;
}
context->state = VOL_LISTENER_STATE_INITIALIZED;
*(int *)p_reply_data = 0;
if (context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) {
check_and_set_gain_dep_cal();
}
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("%s :: cmd called EFFECT_CMD_GET_PARAM", __func__);
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("%s :: cmd called EFFECT_CMD_SET_PARAM", __func__);
break;
case EFFECT_CMD_SET_DEVICE:
{
uint32_t new_device;
bool recompute_gain_dep_cal_Level = false;
ALOGV("cmd called EFFECT_CMD_SET_DEVICE ");
if (p_cmd_data == NULL) {
ALOGE("%s: EFFECT_CMD_SET_DEVICE: cmd data NULL", __func__);
status = -EINVAL;
goto exit;
}
new_device = *(uint32_t *)p_cmd_data;
ALOGV("%s :: EFFECT_CMD_SET_DEVICE: (current/new) device (0x%x / 0x%x)",
__func__, context->dev_id, new_device);
if ((context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) ||
(new_device & AUDIO_DEVICE_OUT_SPEAKER)) {
recompute_gain_dep_cal_Level = true;
}
context->dev_id = new_device;
if (recompute_gain_dep_cal_Level) {
check_and_set_gain_dep_cal();
}
}
break;
case EFFECT_CMD_SET_VOLUME:
{
float left_vol = 0, right_vol = 0;
bool recompute_gain_dep_cal_Level = false;
ALOGV("cmd called EFFECT_CMD_SET_VOLUME");
if (p_cmd_data == NULL || cmd_size != 2 * sizeof(uint32_t)) {
ALOGE("%s: EFFECT_CMD_SET_VOLUME: %s", __func__, (p_cmd_data == NULL) ?
"p_cmd_data is NULL" : "cmd_size issue");
status = -EINVAL;
goto exit;
}
if (context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) {
recompute_gain_dep_cal_Level = true;
}
left_vol = (float)(*(uint32_t *)p_cmd_data) / (1 << 24);
right_vol = (float)(*((uint32_t *)p_cmd_data + 1)) / (1 << 24);
ALOGV("Current Volume (%f / %f ) new Volume (%f / %f)", context->left_vol,
context->right_vol, left_vol, right_vol);
context->left_vol = left_vol;
context->right_vol = right_vol;
if (recompute_gain_dep_cal_Level) {
check_and_set_gain_dep_cal();
}
}
break;
default:
ALOGW("volume_listener_command invalid command %d", cmd_code);
status = -ENOSYS;
break;
}
exit:
pthread_mutex_unlock(&vol_listner_init_lock);
return status;
}
Commit Message: post proc : volume listener : fix effect release crash
Fix access to deleted effect context in vol_prc_lib_release()
Bug: 25753245.
Change-Id: I64ca99e4d5d09667be4c8c605f66700b9ae67949
(cherry picked from commit 93ab6fdda7b7557ccb34372670c30fa6178f8426)
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
(void) RelinquishUniqueFileResource(memory_info->filename);
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline void event_set_filtered_flag(struct trace_event_file *file)
{
unsigned long old_flags = file->flags;
file->flags |= EVENT_FILE_FL_FILTERED;
if (old_flags != file->flags)
trace_buffered_event_enable();
}
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
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: image_transform_png_set_background_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
/* Check for tRNS first: */
if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
image_pixel_add_alpha(that, &display->this);
/* This is only necessary if the alpha value is less than 1. */
if (that->alphaf < 1)
{
/* Now we do the background calculation without any gamma correction. */
if (that->alphaf <= 0)
{
that->redf = data.redf;
that->greenf = data.greenf;
that->bluef = data.bluef;
that->rede = data.rede;
that->greene = data.greene;
that->bluee = data.bluee;
that->red_sBIT= data.red_sBIT;
that->green_sBIT= data.green_sBIT;
that->blue_sBIT= data.blue_sBIT;
}
else /* 0 < alpha < 1 */
{
double alf = 1 - that->alphaf;
that->redf = that->redf * that->alphaf + data.redf * alf;
that->rede = that->rede * that->alphaf + data.rede * alf +
DBL_EPSILON;
that->greenf = that->greenf * that->alphaf + data.greenf * alf;
that->greene = that->greene * that->alphaf + data.greene * alf +
DBL_EPSILON;
that->bluef = that->bluef * that->alphaf + data.bluef * alf;
that->bluee = that->bluee * that->alphaf + data.bluee * alf +
DBL_EPSILON;
}
/* Remove the alpha type and set the alpha (not in that order.) */
that->alphaf = 1;
that->alphae = 0;
if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
that->colour_type = PNG_COLOR_TYPE_RGB;
else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
that->colour_type = PNG_COLOR_TYPE_GRAY;
/* PNG_COLOR_TYPE_PALETTE is not changed */
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (handle != gfx::kNullPluginWindow) {
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return;
}
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id_, params.route_id,
true /* alive */, false /* presented */));
int render_process_id = 0;
int render_widget_id = 0;
if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
params.surface_id, &render_process_id, &render_widget_id)) {
return;
}
RenderWidgetHelper* helper =
RenderWidgetHelper::FromProcessHostID(render_process_id);
if (!helper)
return;
scoped_completion_runner.Release();
helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
render_widget_id,
params.surface_id,
params.surface_handle,
params.route_id,
params.size,
host_id_));
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static int perf_event_stop(struct perf_event *event, int restart)
{
struct stop_event_data sd = {
.event = event,
.restart = restart,
};
int ret = 0;
do {
if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
return 0;
/* matches smp_wmb() in event_sched_in() */
smp_rmb();
/*
* We only want to restart ACTIVE events, so if the event goes
* inactive here (event->oncpu==-1), there's nothing more to do;
* fall through with ret==-ENXIO.
*/
ret = cpu_function_call(READ_ONCE(event->oncpu),
__perf_event_stop, &sd);
} while (ret == -EAGAIN);
return ret;
}
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 <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Alexander Shishkin <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Min Chong <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Fixes: f63a8daa5812 ("perf: Fix event->ctx locking")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-362
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BrowserView::ExitFullscreen() {
if (!IsFullscreen())
return; // Nothing to do.
ProcessFullscreen(false, GURL(), EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: fst_get_iface(struct fst_card_info *card, struct fst_port_info *port,
struct ifreq *ifr)
{
sync_serial_settings sync;
int i;
/* First check what line type is set, we'll default to reporting X.21
* if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be
* changed
*/
switch (port->hwif) {
case E1:
ifr->ifr_settings.type = IF_IFACE_E1;
break;
case T1:
ifr->ifr_settings.type = IF_IFACE_T1;
break;
case V35:
ifr->ifr_settings.type = IF_IFACE_V35;
break;
case V24:
ifr->ifr_settings.type = IF_IFACE_V24;
break;
case X21D:
ifr->ifr_settings.type = IF_IFACE_X21D;
break;
case X21:
default:
ifr->ifr_settings.type = IF_IFACE_X21;
break;
}
if (ifr->ifr_settings.size == 0) {
return 0; /* only type requested */
}
if (ifr->ifr_settings.size < sizeof (sync)) {
return -ENOMEM;
}
i = port->index;
sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed);
/* Lucky card and linux use same encoding here */
sync.clock_type = FST_RDB(card, portConfig[i].internalClock) ==
INTCLK ? CLOCK_INT : CLOCK_EXT;
sync.loopback = 0;
if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) {
return -EFAULT;
}
ifr->ifr_settings.size = sizeof (sync);
return 0;
}
Commit Message: farsync: fix info leak in ioctl
The fst_get_iface() code fails to initialize the two padding bytes of
struct sync_serial_settings after the ->loopback member. Add an explicit
memset(0) before filling the structure to avoid the info leak.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: void BackgroundLoaderOffliner::RenderProcessGone(
base::TerminationStatus status) {
if (pending_request_) {
SavePageRequest request(*pending_request_.get());
switch (status) {
case base::TERMINATION_STATUS_OOM:
case base::TERMINATION_STATUS_PROCESS_CRASHED:
case base::TERMINATION_STATUS_STILL_RUNNING:
std::move(completion_callback_)
.Run(request, Offliner::RequestStatus::LOADING_FAILED_NO_NEXT);
break;
case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
default:
std::move(completion_callback_)
.Run(request, Offliner::RequestStatus::LOADING_FAILED);
}
ResetState();
}
}
Commit Message: Remove unused histograms from the background loader offliner.
Bug: 975512
Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361
Reviewed-by: Cathy Li <[email protected]>
Reviewed-by: Steven Holte <[email protected]>
Commit-Queue: Peter Williamson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#675332}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
unsigned char arg[MAX_ARG_LEN];
struct ip_vs_service_user *usvc_compat;
struct ip_vs_service_user_kern usvc;
struct ip_vs_service *svc;
struct ip_vs_dest_user *udest_compat;
struct ip_vs_dest_user_kern udest;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (len != set_arglen[SET_CMDID(cmd)]) {
pr_err("set_ctl: len %u != %u\n",
len, set_arglen[SET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, len) != 0)
return -EFAULT;
/* increase the module use count */
ip_vs_use_count_inc();
if (mutex_lock_interruptible(&__ip_vs_mutex)) {
ret = -ERESTARTSYS;
goto out_dec;
}
if (cmd == IP_VS_SO_SET_FLUSH) {
/* Flush the virtual service */
ret = ip_vs_flush();
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_TIMEOUT) {
/* Set timeout values for (tcp tcpfin udp) */
ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STARTDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STOPDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = stop_sync_thread(dm->state);
goto out_unlock;
}
usvc_compat = (struct ip_vs_service_user *)arg;
udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
/* We only use the new structs internally, so copy userspace compat
* structs to extended internal versions */
ip_vs_copy_usvc_compat(&usvc, usvc_compat);
ip_vs_copy_udest_compat(&udest, udest_compat);
if (cmd == IP_VS_SO_SET_ZERO) {
/* if no service address is set, zero counters in all */
if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
ret = ip_vs_zero_all();
goto out_unlock;
}
}
/* Check for valid protocol: TCP or UDP, even for fwmark!=0 */
if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) {
pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
usvc.protocol, &usvc.addr.ip,
ntohs(usvc.port), usvc.sched_name);
ret = -EFAULT;
goto out_unlock;
}
/* Lookup the exact service by <protocol, addr, port> or fwmark */
if (usvc.fwmark == 0)
svc = __ip_vs_service_get(usvc.af, usvc.protocol,
&usvc.addr, usvc.port);
else
svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark);
if (cmd != IP_VS_SO_SET_ADD
&& (svc == NULL || svc->protocol != usvc.protocol)) {
ret = -ESRCH;
goto out_unlock;
}
switch (cmd) {
case IP_VS_SO_SET_ADD:
if (svc != NULL)
ret = -EEXIST;
else
ret = ip_vs_add_service(&usvc, &svc);
break;
case IP_VS_SO_SET_EDIT:
ret = ip_vs_edit_service(svc, &usvc);
break;
case IP_VS_SO_SET_DEL:
ret = ip_vs_del_service(svc);
if (!ret)
goto out_unlock;
break;
case IP_VS_SO_SET_ZERO:
ret = ip_vs_zero_service(svc);
break;
case IP_VS_SO_SET_ADDDEST:
ret = ip_vs_add_dest(svc, &udest);
break;
case IP_VS_SO_SET_EDITDEST:
ret = ip_vs_edit_dest(svc, &udest);
break;
case IP_VS_SO_SET_DELDEST:
ret = ip_vs_del_dest(svc, &udest);
break;
default:
ret = -EINVAL;
}
if (svc)
ip_vs_service_put(svc);
out_unlock:
mutex_unlock(&__ip_vs_mutex);
out_dec:
/* decrease the module use count */
ip_vs_use_count_dec();
return ret;
}
Commit Message: ipvs: Add boundary check on ioctl arguments
The ipvs code has a nifty system for doing the size of ioctl command
copies; it defines an array with values into which it indexes the cmd
to find the right length.
Unfortunately, the ipvs code forgot to check if the cmd was in the
range that the array provides, allowing for an index outside of the
array, which then gives a "garbage" result into the length, which
then gets used for copying into a stack buffer.
Fix this by adding sanity checks on these as well as the copy size.
[ [email protected]: adjusted limit to IP_VS_SO_GET_MAX ]
Signed-off-by: Arjan van de Ven <[email protected]>
Acked-by: Julian Anastasov <[email protected]>
Signed-off-by: Simon Horman <[email protected]>
Signed-off-by: Patrick McHardy <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: on_register_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gchar *cfg_desc,
gpointer user_data)
{
struct tcmur_handler *handler;
struct dbus_info *info;
char *bus_name;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
subtype);
handler = g_new0(struct tcmur_handler, 1);
handler->subtype = g_strdup(subtype);
handler->cfg_desc = g_strdup(cfg_desc);
handler->open = dbus_handler_open;
handler->close = dbus_handler_close;
handler->handle_cmd = dbus_handler_handle_cmd;
info = g_new0(struct dbus_info, 1);
info->register_invocation = invocation;
info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
bus_name,
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_handler_appeared,
on_handler_vanished,
handler,
NULL);
g_free(bus_name);
handler->opaque = info;
return TRUE;
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476
Target: 1
Example 2:
Code: void PrintPreviewDialogController::AddObservers(WebContents* contents) {
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(contents));
registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<NavigationController>(&contents->GetController()));
content::Source<content::RenderProcessHost> rph_source(
contents->GetMainFrame()->GetProcess());
if (!registrar_.IsRegistered(this,
content::NOTIFICATION_RENDERER_PROCESS_CLOSED, rph_source)) {
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
rph_source);
host_contents_count_map_[contents->GetMainFrame()->GetProcess()] = 1;
} else {
++host_contents_count_map_[contents->GetMainFrame()->GetProcess()];
}
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: update_person(person_t* person, bool* out_has_moved)
{
struct command command;
double delta_x, delta_y;
int facing;
bool has_moved;
bool is_finished;
const person_t* last_person;
struct step step;
int vector;
int i;
person->mv_x = 0; person->mv_y = 0;
if (person->revert_frames > 0 && --person->revert_frames <= 0)
person->frame = 0;
if (person->leader == NULL) { // no leader; use command queue
if (person->num_commands == 0)
person_activate(person, PERSON_SCRIPT_GENERATOR, NULL, true);
is_finished = !does_person_exist(person) || person->num_commands == 0;
while (!is_finished) {
command = person->commands[0];
--person->num_commands;
for (i = 0; i < person->num_commands; ++i)
person->commands[i] = person->commands[i + 1];
last_person = s_current_person;
s_current_person = person;
if (command.type != COMMAND_RUN_SCRIPT)
command_person(person, command.type);
else
script_run(command.script, false);
s_current_person = last_person;
script_unref(command.script);
is_finished = !does_person_exist(person) // stop if person was destroyed
|| !command.is_immediate || person->num_commands == 0;
}
}
else { // leader set; follow the leader!
step = person->leader->steps[person->follow_distance - 1];
delta_x = step.x - person->x;
delta_y = step.y - person->y;
if (fabs(delta_x) > person->speed_x)
command_person(person, delta_x > 0 ? COMMAND_MOVE_EAST : COMMAND_MOVE_WEST);
if (!does_person_exist(person)) return;
if (fabs(delta_y) > person->speed_y)
command_person(person, delta_y > 0 ? COMMAND_MOVE_SOUTH : COMMAND_MOVE_NORTH);
if (!does_person_exist(person)) return;
vector = person->mv_x + person->mv_y * 3;
facing = vector == -3 ? COMMAND_FACE_NORTH
: vector == -2 ? COMMAND_FACE_NORTHEAST
: vector == 1 ? COMMAND_FACE_EAST
: vector == 4 ? COMMAND_FACE_SOUTHEAST
: vector == 3 ? COMMAND_FACE_SOUTH
: vector == 2 ? COMMAND_FACE_SOUTHWEST
: vector == -1 ? COMMAND_FACE_WEST
: vector == -4 ? COMMAND_FACE_NORTHWEST
: COMMAND_WAIT;
if (facing != COMMAND_WAIT)
command_person(person, COMMAND_ANIMATE);
if (!does_person_exist(person)) return;
command_person(person, facing);
}
if (!does_person_exist(person))
return; // they probably got eaten by a pig.
*out_has_moved = person_has_moved(person);
if (*out_has_moved)
record_step(person);
for (i = 0; i < s_num_persons; ++i) {
if (s_persons[i]->leader != person)
continue;
update_person(s_persons[i], &has_moved);
*out_has_moved |= has_moved;
}
}
Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268)
* Fix integer overflow in layer_resize in map_engine.c
There's a buffer overflow bug in the function layer_resize. It allocates
a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`.
But it didn't check for integer overflow, so if x_size and y_size are
very large, it's possible that the buffer size is smaller than needed,
causing a buffer overflow later.
PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);`
* move malloc to a separate line
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
Commit Message: aio: fix kernel memory disclosure in io_getevents() introduced in v3.10
A kernel memory disclosure was introduced in aio_read_events_ring() in v3.10
by commit a31ad380bed817aa25f8830ad23e1a0480fef797. The changes made to
aio_read_events_ring() failed to correctly limit the index into
ctx->ring_pages[], allowing an attacked to cause the subsequent kmap() of
an arbitrary page with a copy_to_user() to copy the contents into userspace.
This vulnerability has been assigned CVE-2014-0206. Thanks to Mateusz and
Petr for disclosing this issue.
This patch applies to v3.12+. A separate backport is needed for 3.10/3.11.
Signed-off-by: Benjamin LaHaise <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Kent Overstreet <[email protected]>
Cc: Jeff Moyer <[email protected]>
Cc: [email protected]
CWE ID:
Target: 1
Example 2:
Code: unsigned long iov_iter_gap_alignment(const struct iov_iter *i)
{
unsigned long res = 0;
size_t size = i->count;
if (unlikely(i->type & ITER_PIPE)) {
WARN_ON(1);
return ~0U;
}
iterate_all_kinds(i, size, v,
(res |= (!res ? 0 : (unsigned long)v.iov_base) |
(size != v.iov_len ? size : 0), 0),
(res |= (!res ? 0 : (unsigned long)v.bv_offset) |
(size != v.bv_len ? size : 0)),
(res |= (!res ? 0 : (unsigned long)v.iov_base) |
(size != v.iov_len ? size : 0))
);
return res;
}
Commit Message: fix a fencepost error in pipe_advance()
The logics in pipe_advance() used to release all buffers past the new
position failed in cases when the number of buffers to release was equal
to pipe->buffers. If that happened, none of them had been released,
leaving pipe full. Worse, it was trivial to trigger and we end up with
pipe full of uninitialized pages. IOW, it's an infoleak.
Cc: [email protected] # v4.9
Reported-by: "Alan J. Wylie" <[email protected]>
Tested-by: "Alan J. Wylie" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name,
int aid, int novar, xsltAxis axis) {
xmlChar *lit = NULL;
xmlChar *lit2 = NULL;
if (CUR != '(') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ( expected\n");
ctxt->error = 1;
return;
}
if ((aid) && (xmlStrEqual(name, (const xmlChar *)"id"))) {
if (axis != 0) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : NodeTest expected\n");
ctxt->error = 1;
return;
}
NEXT;
SKIP_BLANKS;
lit = xsltScanLiteral(ctxt);
if (ctxt->error) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : Literal expected\n");
return;
}
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
xmlFree(lit);
ctxt->error = 1;
return;
}
NEXT;
PUSH(XSLT_OP_ID, lit, NULL, novar);
lit = NULL;
} else if ((aid) && (xmlStrEqual(name, (const xmlChar *)"key"))) {
if (axis != 0) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : NodeTest expected\n");
ctxt->error = 1;
return;
}
NEXT;
SKIP_BLANKS;
lit = xsltScanLiteral(ctxt);
if (ctxt->error) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : Literal expected\n");
return;
}
SKIP_BLANKS;
if (CUR != ',') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : , expected\n");
ctxt->error = 1;
return;
}
NEXT;
SKIP_BLANKS;
lit2 = xsltScanLiteral(ctxt);
if (ctxt->error) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : Literal expected\n");
xmlFree(lit);
return;
}
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
xmlFree(lit);
xmlFree(lit2);
ctxt->error = 1;
return;
}
NEXT;
/* URGENT TODO: support namespace in keys */
PUSH(XSLT_OP_KEY, lit, lit2, novar);
lit = NULL;
lit2 = NULL;
} else if (xmlStrEqual(name, (const xmlChar *)"processing-instruction")) {
NEXT;
SKIP_BLANKS;
if (CUR != ')') {
lit = xsltScanLiteral(ctxt);
if (ctxt->error) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : Literal expected\n");
return;
}
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
ctxt->error = 1;
return;
}
}
NEXT;
PUSH(XSLT_OP_PI, lit, NULL, novar);
lit = NULL;
} else if (xmlStrEqual(name, (const xmlChar *)"text")) {
NEXT;
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
ctxt->error = 1;
return;
}
NEXT;
PUSH(XSLT_OP_TEXT, NULL, NULL, novar);
} else if (xmlStrEqual(name, (const xmlChar *)"comment")) {
NEXT;
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
ctxt->error = 1;
return;
}
NEXT;
PUSH(XSLT_OP_COMMENT, NULL, NULL, novar);
} else if (xmlStrEqual(name, (const xmlChar *)"node")) {
NEXT;
SKIP_BLANKS;
if (CUR != ')') {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : ) expected\n");
ctxt->error = 1;
return;
}
NEXT;
if (axis == AXIS_ATTRIBUTE) {
PUSH(XSLT_OP_ATTR, NULL, NULL, novar);
}
else {
PUSH(XSLT_OP_NODE, NULL, NULL, novar);
}
} else if (aid) {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : expecting 'key' or 'id' or node type\n");
ctxt->error = 1;
return;
} else {
xsltTransformError(NULL, NULL, NULL,
"xsltCompileIdKeyPattern : node type\n");
ctxt->error = 1;
return;
}
error:
return;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
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))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
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 <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLMediaElement::setMuted(bool muted) {
BLINK_MEDIA_LOG << "setMuted(" << (void*)this << ", " << BoolString(muted)
<< ")";
if (muted_ == muted)
return;
muted_ = muted;
ScheduleEvent(EventTypeNames::volumechange);
if (!muted_ && !autoplay_policy_->RequestAutoplayUnmute())
pause();
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetVolume(EffectiveMediaVolume());
autoplay_policy_->StopAutoplayMutedWhenVisible();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __kprobes perf_event_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *__args)
{
struct die_args *args = __args;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int i;
if (!atomic_read(&active_events))
return NOTIFY_DONE;
switch (cmd) {
case DIE_NMI:
break;
default:
return NOTIFY_DONE;
}
regs = args->regs;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/* If the PMU has the TOE IRQ enable bits, we need to do a
* dummy write to the %pcr to clear the overflow bits and thus
* the interrupt.
*
* Do this before we peek at the counters to determine
* overflow so we don't lose any events.
*/
if (sparc_pmu->irq_bit)
pcr_ops->write(cpuc->pcr);
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *event = cpuc->event[i];
int idx = cpuc->current_idx[i];
struct hw_perf_event *hwc;
u64 val;
hwc = &event->hw;
val = sparc_perf_event_update(event, hwc, idx);
if (val & (1ULL << 31))
continue;
data.period = event->hw.last_period;
if (!sparc_perf_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 1, &data, regs))
sparc_pmu_stop(event, 0);
}
return NOTIFY_STOP;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < CHDLC_HDRLEN) {
ND_PRINT((ndo, "[|chdlc]"));
return (caplen);
}
return (chdlc_print(ndo, p,length));
}
Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks.
Prevent a possible buffer overread in chdlc_print() and replace the
custom check in chdlc_if_print() with a standard check in chdlc_print()
so that the latter certainly does not over-read even when reached via
juniper_chdlc_print(). Add length checks.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void bmdma_start_dma(IDEDMA *dma, IDEState *s,
BlockCompletionFunc *dma_cb)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
bm->unit = s->unit;
bm->dma_cb = dma_cb;
bm->cur_prd_last = 0;
bm->cur_prd_addr = 0;
bm->cur_prd_len = 0;
bm->sector_num = ide_get_sector(s);
bm->nsector = s->nsector;
if (bm->status & BM_STATUS_DMAING) {
bm->dma_cb(bmdma_active_if(bm), 0);
}
}
Commit Message:
CWE ID: CWE-399
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Read(cc::mojom::CompositorFrameMetadataDataView data,
cc::CompositorFrameMetadata* out) {
out->device_scale_factor = data.device_scale_factor();
if (!data.ReadRootScrollOffset(&out->root_scroll_offset))
return false;
out->page_scale_factor = data.page_scale_factor();
if (!data.ReadScrollableViewportSize(&out->scrollable_viewport_size) ||
!data.ReadRootLayerSize(&out->root_layer_size)) {
return false;
}
out->min_page_scale_factor = data.min_page_scale_factor();
out->max_page_scale_factor = data.max_page_scale_factor();
out->root_overflow_x_hidden = data.root_overflow_x_hidden();
out->root_overflow_y_hidden = data.root_overflow_y_hidden();
out->may_contain_video = data.may_contain_video();
out->is_resourceless_software_draw_with_scroll_or_animation =
data.is_resourceless_software_draw_with_scroll_or_animation();
out->top_controls_height = data.top_controls_height();
out->top_controls_shown_ratio = data.top_controls_shown_ratio();
out->bottom_controls_height = data.bottom_controls_height();
out->bottom_controls_shown_ratio = data.bottom_controls_shown_ratio();
out->root_background_color = data.root_background_color();
out->can_activate_before_dependencies =
data.can_activate_before_dependencies();
return data.ReadSelection(&out->selection) &&
data.ReadLatencyInfo(&out->latency_info) &&
data.ReadReferencedSurfaces(&out->referenced_surfaces);
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ID3::Iterator::getstring(String8 *id, bool otherdata) const {
id->setTo("");
const uint8_t *frameData = mFrameData;
if (frameData == NULL) {
return;
}
uint8_t encoding = *frameData;
if (mParent.mVersion == ID3_V1 || mParent.mVersion == ID3_V1_1) {
if (mOffset == 126 || mOffset == 127) {
char tmp[16];
sprintf(tmp, "%d", (int)*frameData);
id->setTo(tmp);
return;
}
id->setTo((const char*)frameData, mFrameSize);
return;
}
if (mFrameSize < getHeaderLength() + 1) {
return;
}
size_t n = mFrameSize - getHeaderLength() - 1;
if (otherdata) {
frameData += 4;
int32_t i = n - 4;
while(--i >= 0 && *++frameData != 0) ;
int skipped = (frameData - mFrameData);
if (skipped >= (int)n) {
return;
}
n -= skipped;
}
if (encoding == 0x00) {
id->setTo((const char*)frameData + 1, n);
} else if (encoding == 0x03) {
id->setTo((const char *)(frameData + 1), n);
} else if (encoding == 0x02) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
#if BYTE_ORDER == LITTLE_ENDIAN
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
#endif
id->setTo(framedata, len);
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
} else if (encoding == 0x01) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
if (*framedata == 0xfffe) {
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
}
if (*framedata == 0xfeff) {
framedata++;
len--;
}
bool eightBit = true;
for (int i = 0; i < len; i++) {
if (framedata[i] > 0xff) {
eightBit = false;
break;
}
}
if (eightBit) {
char *frame8 = new char[len];
for (int i = 0; i < len; i++) {
frame8[i] = framedata[i];
}
id->setTo(frame8, len);
delete [] frame8;
} else {
id->setTo(framedata, len);
}
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
}
}
Commit Message: better validation lengths of strings in ID3 tags
Validate lengths on strings in ID3 tags, particularly around 0.
Also added code to handle cases when we can't get memory for
copies of strings we want to extract from these tags.
Affects L/M/N/master, same patch for all of them.
Bug: 30744884
Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e
Test: play mp3 file which caused a <0 length.
(cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f)
CWE ID: CWE-20
Target: 1
Example 2:
Code: static time_t gf_mktime_utc(struct tm *tm)
{
static const u32 days_per_month[2][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
time_t time=0;
int i;
for (i=70; i<tm->tm_year; i++) {
time += leap_year(i) ? 366 : 365;
}
for (i=0; i<tm->tm_mon; ++i) {
time += days_per_month[leap_year(tm->tm_year)][i];
}
time += tm->tm_mday - 1;
time *= 24;
time += tm->tm_hour;
time *= 60;
time += tm->tm_min;
time *= 60;
time += tm->tm_sec;
return time;
}
Commit Message: fix buffer overrun in gf_bin128_parse
closes #1204
closes #1205
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N)
{
/* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */
BIGNUM *u;
unsigned char cu[SHA_DIGEST_LENGTH];
unsigned char *cAB;
EVP_MD_CTX ctxt;
int longN;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
longN= BN_num_bytes(N);
if ((cAB = OPENSSL_malloc(2*longN)) == NULL)
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN);
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN);
OPENSSL_free(cAB);
EVP_DigestFinal_ex(&ctxt, cu, NULL);
EVP_MD_CTX_cleanup(&ctxt);
if (!(u = BN_bin2bn(cu, sizeof(cu), NULL)))
return NULL;
if (!BN_is_zero(u))
return u;
BN_free(u);
return NULL;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,
const char *text, int size, int xoff, int yoff,
uint32_t colour)
{
int i, ret;
int len = text ? strlen(text) : 0;
struct dstr str = {0, 0, 0};
/* Don't bother adding empty/null strings */
if (!len)
return 0;
dstr_append(&str, "BT ");
dstr_printf(&str, "%d %d TD ", xoff, yoff);
dstr_printf(&str, "/F%d %d Tf ",
pdf->current_font->font.index, size);
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_append(&str, "(");
/* Escape magic characters properly */
for (i = 0; i < len; ) {
uint32_t code;
int code_len;
code_len = utf8_to_utf32(&text[i], len - i, &code);
if (code_len < 0) {
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Invalid UTF-8 encoding");
}
if (code > 255) {
/* We support *some* minimal UTF-8 characters */
char buf[5] = {0};
switch (code) {
case 0x160:
buf[0] = (char)0x8a;
break;
case 0x161:
buf[0] = (char)0x9a;
break;
case 0x17d:
buf[0] = (char)0x8e;
break;
case 0x17e:
buf[0] = (char)0x9e;
break;
case 0x20ac:
strcpy(buf, "\\200");
break;
default:
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Unsupported UTF-8 character: 0x%x 0o%o", code, code);
}
dstr_append(&str, buf);
} else if (strchr("()\\", code)) {
char buf[3];
/* Escape some characters */
buf[0] = '\\';
buf[1] = code;
buf[2] = '\0';
dstr_append(&str, buf);
} else if (strrchr("\n\r\t\b\f", code)) {
/* Skip over these characters */
;
} else {
char buf[2];
buf[0] = code;
buf[1] = '\0';
dstr_append(&str, buf);
}
i += code_len;
}
dstr_append(&str, ") Tj ");
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
Commit Message: jpeg: Fix another possible buffer overrun
Found via the clang libfuzzer
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len,
const unsigned char *limit)
{
/* This is used only by servers. */
SSL_SESSION *ret = NULL;
int fatal = 0;
int try_session_cache = 1;
#ifndef OPENSSL_NO_TLSEXT
int r;
#endif
if (session_id + len > limit) {
fatal = 1;
goto err;
}
if (len == 0)
try_session_cache = 0;
#ifndef OPENSSL_NO_TLSEXT
/* sets s->tlsext_ticket_expected */
r = tls1_process_ticket(s, session_id, len, limit, &ret);
switch (r) {
case -1: /* Error during processing */
fatal = 1;
goto err;
case 0: /* No ticket found */
case 1: /* Zero length ticket found */
break; /* Ok to carry on processing session id. */
case 2: /* Ticket found but not decrypted. */
case 3: /* Ticket decrypted, *ret has been set. */
try_session_cache = 0;
break;
default:
abort();
}
#endif
if (try_session_cache &&
ret == NULL &&
!(s->session_ctx->session_cache_mode &
SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
SSL_SESSION data;
data.ssl_version = s->version;
data.session_id_length = len;
if (len == 0)
return 0;
memcpy(data.session_id, session_id, len);
CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
if (ret != NULL) {
/* don't allow other threads to steal it: */
CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);
}
CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
if (ret == NULL)
s->session_ctx->stats.sess_miss++;
}
if (try_session_cache &&
ret == NULL && s->session_ctx->get_session_cb != NULL) {
int copy = 1;
if ((ret = s->session_ctx->get_session_cb(s, session_id, len, ©))) {
s->session_ctx->stats.sess_cb_hit++;
/*
* Increment reference count now if the session callback asks us
* to do so (note that if the session structures returned by the
* callback are shared between threads, it must handle the
* reference count itself [i.e. copy == 0], or things won't be
* thread-safe).
*/
if (copy)
CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);
/*
* Add the externally cached session to the internal cache as
* well if and only if we are supposed to.
*/
if (!
(s->session_ctx->session_cache_mode &
SSL_SESS_CACHE_NO_INTERNAL_STORE))
/*
* The following should not return 1, otherwise, things are
* very strange
*/
SSL_CTX_add_session(s->session_ctx, ret);
}
}
if (ret == NULL)
goto err;
/* Now ret is non-NULL and we own one of its reference counts. */
if (ret->sid_ctx_length != s->sid_ctx_length
|| memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
/*
* We have the session requested by the client, but we don't want to
* use it in this context.
*/
goto err; /* treat like cache miss */
}
if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
/*
* We can't be sure if this session is being used out of context,
* which is especially important for SSL_VERIFY_PEER. The application
* should have used SSL[_CTX]_set_session_id_context. For this error
* case, we generate an error instead of treating the event like a
* cache miss (otherwise it would be easy for applications to
* effectively disable the session cache by accident without anyone
* noticing).
*/
SSLerr(SSL_F_SSL_GET_PREV_SESSION,
SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
fatal = 1;
goto err;
}
if (ret->cipher == NULL) {
unsigned char buf[5], *p;
unsigned long l;
p = buf;
l = ret->cipher_id;
l2n(l, p);
if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR)
ret->cipher = ssl_get_cipher_by_char(s, &(buf[2]));
else
ret->cipher = ssl_get_cipher_by_char(s, &(buf[1]));
if (ret->cipher == NULL)
goto err;
}
if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
s->session_ctx->stats.sess_timeout++;
if (try_session_cache) {
/* session was from the cache, so remove it */
SSL_CTX_remove_session(s->session_ctx, ret);
}
goto err;
}
s->session_ctx->stats.sess_hit++;
if (s->session != NULL)
SSL_SESSION_free(s->session);
s->session = ret;
s->verify_result = s->session->verify_result;
return 1;
err:
if (ret != NULL) {
SSL_SESSION_free(ret);
#ifndef OPENSSL_NO_TLSEXT
if (!try_session_cache) {
/*
* The session was from a ticket, so we should issue a ticket for
* the new session
*/
s->tlsext_ticket_expected = 1;
}
#endif
}
if (fatal)
return -1;
else
return 0;
}
Commit Message:
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ixheaacd_cmplx_anal_fft != NULL)
(*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int getoptions(char *c, struct trusted_key_payload *pay,
struct trusted_key_options *opt)
{
substring_t args[MAX_OPT_ARGS];
char *p = c;
int token;
int res;
unsigned long handle;
unsigned long lock;
while ((p = strsep(&c, " \t"))) {
if (*p == '\0' || *p == ' ' || *p == '\t')
continue;
token = match_token(p, key_tokens, args);
switch (token) {
case Opt_pcrinfo:
opt->pcrinfo_len = strlen(args[0].from) / 2;
if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
return -EINVAL;
res = hex2bin(opt->pcrinfo, args[0].from,
opt->pcrinfo_len);
if (res < 0)
return -EINVAL;
break;
case Opt_keyhandle:
res = kstrtoul(args[0].from, 16, &handle);
if (res < 0)
return -EINVAL;
opt->keytype = SEAL_keytype;
opt->keyhandle = handle;
break;
case Opt_keyauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->keyauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_blobauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->blobauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_migratable:
if (*args[0].from == '0')
pay->migratable = 0;
else
return -EINVAL;
break;
case Opt_pcrlock:
res = kstrtoul(args[0].from, 10, &lock);
if (res < 0)
return -EINVAL;
opt->pcrlock = lock;
break;
default:
return -EINVAL;
}
}
return 0;
}
Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key
If a user key gets negatively instantiated, an error code is cached in the
payload area. A negatively instantiated key may be then be positively
instantiated by updating it with valid data. However, the ->update key
type method must be aware that the error code may be there.
The following may be used to trigger the bug in the user key type:
keyctl request2 user user "" @u
keyctl add user user "a" @u
which manifests itself as:
BUG: unable to handle kernel paging request at 00000000ffffff8a
IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
PGD 7cc30067 PUD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000
RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280
[<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246
RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001
RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82
RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000
R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82
R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700
FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0
Stack:
ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82
ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5
ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620
Call Trace:
[<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136
[<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129
[< inline >] __key_update security/keys/key.c:730
[<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908
[< inline >] SYSC_add_key security/keys/keyctl.c:125
[<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60
[<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185
Note the error code (-ENOKEY) in EDX.
A similar bug can be tripped by:
keyctl request2 trusted user "" @u
keyctl add trusted user "a" @u
This should also affect encrypted keys - but that has to be correctly
parameterised or it will fail with EINVAL before getting to the bit that
will crashes.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsAndroid::SetHasPendingNavigationTransitionForTesting(
JNIEnv* env,
jobject obj) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
RenderFrameHost* frame =
static_cast<WebContentsImpl*>(web_contents_)->GetMainFrame();
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(
&TransitionRequestManager::AddPendingTransitionRequestDataForTesting,
base::Unretained(TransitionRequestManager::GetInstance()),
frame->GetProcess()->GetID(),
frame->GetRoutingID()));
}
Commit Message: Revert "Load web contents after tab is created."
This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d.
BUG=432562
[email protected],[email protected],[email protected]
Review URL: https://codereview.chromium.org/894003005
Cr-Commit-Position: refs/heads/master@{#314469}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int _yr_scan_verify_re_match(
YR_SCAN_CONTEXT* context,
YR_AC_MATCH* ac_match,
uint8_t* data,
size_t data_size,
size_t data_base,
size_t offset)
{
CALLBACK_ARGS callback_args;
RE_EXEC_FUNC exec;
int forward_matches = -1;
int backward_matches = -1;
int flags = 0;
if (STRING_IS_GREEDY_REGEXP(ac_match->string))
flags |= RE_FLAGS_GREEDY;
if (STRING_IS_NO_CASE(ac_match->string))
flags |= RE_FLAGS_NO_CASE;
if (STRING_IS_DOT_ALL(ac_match->string))
flags |= RE_FLAGS_DOT_ALL;
if (STRING_IS_FAST_REGEXP(ac_match->string))
exec = yr_re_fast_exec;
else
exec = yr_re_exec;
if (STRING_IS_ASCII(ac_match->string))
{
forward_matches = exec(
ac_match->forward_code,
data + offset,
data_size - offset,
offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags,
NULL,
NULL);
}
if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1)
{
flags |= RE_FLAGS_WIDE;
forward_matches = exec(
ac_match->forward_code,
data + offset,
data_size - offset,
offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags,
NULL,
NULL);
}
switch(forward_matches)
{
case -1:
return ERROR_SUCCESS;
case -2:
return ERROR_INSUFFICIENT_MEMORY;
case -3:
return ERROR_TOO_MANY_MATCHES;
case -4:
return ERROR_TOO_MANY_RE_FIBERS;
case -5:
return ERROR_INTERNAL_FATAL_ERROR;
}
if (forward_matches == 0 && ac_match->backward_code == NULL)
return ERROR_SUCCESS;
callback_args.string = ac_match->string;
callback_args.context = context;
callback_args.data = data;
callback_args.data_size = data_size;
callback_args.data_base = data_base;
callback_args.forward_matches = forward_matches;
callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string);
if (ac_match->backward_code != NULL)
{
backward_matches = exec(
ac_match->backward_code,
data + offset,
offset,
flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE,
_yr_scan_match_callback,
(void*) &callback_args);
switch(backward_matches)
{
case -2:
return ERROR_INSUFFICIENT_MEMORY;
case -3:
return ERROR_TOO_MANY_MATCHES;
case -4:
return ERROR_TOO_MANY_RE_FIBERS;
case -5:
return ERROR_INTERNAL_FATAL_ERROR;
}
}
else
{
FAIL_ON_ERROR(_yr_scan_match_callback(
data + offset, 0, flags, &callback_args));
}
return ERROR_SUCCESS;
}
Commit Message: Fix issue #646 (#648)
* Fix issue #646 and some edge cases with wide regexps using \b and \B
* Rename function IS_WORD_CHAR to _yr_re_is_word_char
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Gfx::doRadialShFill(GfxRadialShading *shading) {
double xMin, yMin, xMax, yMax;
double x0, y0, r0, x1, y1, r1, t0, t1;
int nComps;
GfxColor colorA, colorB;
double xa, ya, xb, yb, ra, rb;
double ta, tb, sa, sb;
double sz, xz, yz, sMin, sMax;
GBool enclosed;
int ia, ib, k, n;
double *ctm;
double theta, alpha, angle, t;
GBool needExtend = gTrue;
shading->getCoords(&x0, &y0, &r0, &x1, &y1, &r1);
t0 = shading->getDomain0();
t1 = shading->getDomain1();
nComps = shading->getColorSpace()->getNComps();
if (x0 == x1 && y0 == y1) {
enclosed = gTrue;
theta = 0; // make gcc happy
sz = 0; // make gcc happy
} else if (r0 == r1) {
enclosed = gFalse;
theta = 0;
sz = 0; // make gcc happy
} else {
sz = -r0 / (r1 - r0);
xz = x0 + sz * (x1 - x0);
yz = y0 + sz * (y1 - y0);
enclosed = (xz - x0) * (xz - x0) + (yz - y0) * (yz - y0) <= r0 * r0;
theta = asin(r0 / sqrt((x0 - xz) * (x0 - xz) + (y0 - yz) * (y0 - yz)));
if (r0 > r1) {
theta = -theta;
}
}
if (enclosed) {
alpha = 0;
} else {
alpha = atan2(y1 - y0, x1 - x0);
}
state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
if (enclosed) {
sMin = 0;
sMax = 1;
} else {
sMin = 1;
sMax = 0;
if ((x1 + r1) - (x0 + r0) != 0) {
sa = (xMin - (x0 + r0)) / ((x1 + r1) - (x0 + r0));
if (sa < sMin) {
sMin = sa;
} else if (sa > sMax) {
sMax = sa;
}
}
if ((x1 - r1) - (x0 - r0) != 0) {
sa = (xMax - (x0 - r0)) / ((x1 - r1) - (x0 - r0));
if (sa < sMin) {
sMin = sa;
} else if (sa > sMax) {
sMax = sa;
}
}
if ((y1 + r1) - (y0 + r0) != 0) {
sa = (yMin - (y0 + r0)) / ((y1 + r1) - (y0 + r0));
if (sa < sMin) {
sMin = sa;
} else if (sa > sMax) {
sMax = sa;
}
}
if ((y1 - r1) - (y0 - r0) != 0) {
sa = (yMax - (y0 - r0)) / ((y1 - r1) - (y0 - r0));
if (sa < sMin) {
sMin = sa;
} else if (sa > sMax) {
sMax = sa;
}
}
if (r0 < r1) {
if (sMin < sz) {
sMin = sz;
}
} else if (r0 > r1) {
if (sMax > sz) {
sMax = sz;
}
}
if (!shading->getExtend0() && sMin < 0) {
sMin = 0;
}
if (!shading->getExtend1() && sMax > 1) {
sMax = 1;
}
}
if (out->useShadedFills() &&
out->radialShadedFill(state, shading, sMin, sMax)) {
return;
}
ctm = state->getCTM();
t = fabs(ctm[0]);
if (fabs(ctm[1]) > t) {
t = fabs(ctm[1]);
}
if (fabs(ctm[2]) > t) {
t = fabs(ctm[2]);
}
if (fabs(ctm[3]) > t) {
t = fabs(ctm[3]);
}
if (r0 > r1) {
t *= r0;
} else {
t *= r1;
}
if (t < 1) {
n = 3;
} else {
n = (int)(M_PI / acos(1 - 0.1 / t));
if (n < 3) {
n = 3;
} else if (n > 200) {
n = 200;
}
}
ia = 0;
sa = sMin;
ta = t0 + sa * (t1 - t0);
xa = x0 + sa * (x1 - x0);
ya = y0 + sa * (y1 - y0);
ra = r0 + sa * (r1 - r0);
if (ta < t0) {
shading->getColor(t0, &colorA);
} else if (ta > t1) {
shading->getColor(t1, &colorA);
} else {
shading->getColor(ta, &colorA);
}
needExtend = !out->radialShadedSupportExtend(state, shading);
while (ia < radialMaxSplits) {
ib = radialMaxSplits;
sb = sMax;
tb = t0 + sb * (t1 - t0);
if (tb < t0) {
shading->getColor(t0, &colorB);
} else if (tb > t1) {
shading->getColor(t1, &colorB);
} else {
shading->getColor(tb, &colorB);
}
while (ib - ia > 1) {
if (isSameGfxColor(colorB, colorA, nComps, radialColorDelta) && ib < radialMaxSplits) {
GfxColor colorC;
int ic = (ia + ib) / 2;
double sc = sMin + ((double)ic / (double)radialMaxSplits) * (sMax - sMin);
double tc = t0 + sc * (t1 - t0);
if (tc < t0) {
shading->getColor(t0, &colorC);
} else if (tc > t1) {
shading->getColor(t1, &colorC);
} else {
shading->getColor(tc, &colorC);
}
if (isSameGfxColor(colorC, colorA, nComps, radialColorDelta))
break;
}
ib = (ia + ib) / 2;
sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
tb = t0 + sb * (t1 - t0);
if (tb < t0) {
shading->getColor(t0, &colorB);
} else if (tb > t1) {
shading->getColor(t1, &colorB);
} else {
shading->getColor(tb, &colorB);
}
}
xb = x0 + sb * (x1 - x0);
yb = y0 + sb * (y1 - y0);
rb = r0 + sb * (r1 - r0);
for (k = 0; k < nComps; ++k) {
colorA.c[k] = (colorA.c[k] + colorB.c[k]) / 2;
}
state->setFillColor(&colorA);
if (out->useFillColorStop())
out->updateFillColorStop(state, (sa - sMin)/(sMax - sMin));
else
out->updateFillColor(state);
if (needExtend) {
if (enclosed) {
state->moveTo(xa + ra, ya);
for (k = 1; k < n; ++k) {
angle = ((double)k / (double)n) * 2 * M_PI;
state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
}
state->closePath();
state->moveTo(xb + rb, yb);
for (k = 1; k < n; ++k) {
angle = -((double)k / (double)n) * 2 * M_PI;
state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
}
state->closePath();
} else {
state->moveTo(xa + ra * cos(alpha + theta + 0.5 * M_PI),
ya + ra * sin(alpha + theta + 0.5 * M_PI));
for (k = 0; k < n; ++k) {
angle = alpha + theta + 0.5 * M_PI
- ((double)k / (double)n) * (2 * theta + M_PI);
state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
}
for (k = 0; k < n; ++k) {
angle = alpha - theta - 0.5 * M_PI
+ ((double)k / (double)n) * (2 * theta - M_PI);
state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
}
state->closePath();
state->moveTo(xa + ra * cos(alpha + theta + 0.5 * M_PI),
ya + ra * sin(alpha + theta + 0.5 * M_PI));
for (k = 0; k < n; ++k) {
angle = alpha + theta + 0.5 * M_PI
+ ((double)k / (double)n) * (-2 * theta + M_PI);
state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
}
for (k = 0; k < n; ++k) {
angle = alpha - theta - 0.5 * M_PI
+ ((double)k / (double)n) * (2 * theta + M_PI);
state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
}
state->closePath();
}
}
if (!out->useFillColorStop()) {
if (!contentIsHidden())
out->fill(state);
state->clearPath();
}
ia = ib;
sa = sb;
ta = tb;
xa = xb;
ya = yb;
ra = rb;
colorA = colorB;
}
if (out->useFillColorStop()) {
state->setFillColor(&colorA);
out->updateFillColorStop(state, (sb - sMin)/(sMax - sMin));
state->moveTo(xMin, yMin);
state->lineTo(xMin, yMax);
state->lineTo(xMax, yMax);
state->lineTo(xMax, yMin);
state->closePath();
if (!contentIsHidden())
out->fill(state);
state->clearPath();
}
if (!needExtend)
return;
if (enclosed) {
if ((shading->getExtend0() && r0 <= r1) ||
(shading->getExtend1() && r1 < r0)) {
if (r0 <= r1) {
ta = t0;
ra = r0;
xa = x0;
ya = y0;
} else {
ta = t1;
ra = r1;
xa = x1;
ya = y1;
}
shading->getColor(ta, &colorA);
state->setFillColor(&colorA);
out->updateFillColor(state);
state->moveTo(xa + ra, ya);
for (k = 1; k < n; ++k) {
angle = ((double)k / (double)n) * 2 * M_PI;
state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
}
state->closePath();
if (!contentIsHidden())
out->fill(state);
state->clearPath();
}
if ((shading->getExtend0() && r0 > r1) ||
(shading->getExtend1() && r1 >= r0)) {
if (r0 > r1) {
ta = t0;
ra = r0;
xa = x0;
ya = y0;
} else {
ta = t1;
ra = r1;
xa = x1;
ya = y1;
}
shading->getColor(ta, &colorA);
state->setFillColor(&colorA);
out->updateFillColor(state);
state->moveTo(xMin, yMin);
state->lineTo(xMin, yMax);
state->lineTo(xMax, yMax);
state->lineTo(xMax, yMin);
state->closePath();
state->moveTo(xa + ra, ya);
for (k = 1; k < n; ++k) {
angle = ((double)k / (double)n) * 2 * M_PI;
state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
}
state->closePath();
if (!contentIsHidden())
out->fill(state);
state->clearPath();
}
}
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void agent_cancel_query(agent_pending_query *q)
{
assert(0 && "Windows agent queries are never asynchronous!");
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 > len) {
return op->size;
}
int min_val = (ut32)(UINT (data, pos + 4)),
max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op()
CWE ID: CWE-125
Target: 1
Example 2:
Code: read_byte(bmp_source_ptr sinfo)
/* Read next byte from BMP file */
{
register FILE *infile = sinfo->pub.input_file;
register int c;
if ((c = getc(infile)) == EOF)
ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
return c;
}
Commit Message: tjLoadImage(): Fix FPE triggered by malformed BMP
In rdbmp.c, it is necessary to guard against 32-bit overflow/wraparound
when allocating the row buffer, because since BMP files have 32-bit
width and height fields, the value of biWidth can be up to 4294967295.
Specifically, if biWidth is 1073741824 and cinfo->input_components = 4,
then the samplesperrow argument in alloc_sarray() would wrap around to
0, and a division by zero error would occur at line 458 in jmemmgr.c.
If biWidth is set to a higher value, then samplesperrow would wrap
around to a small number, which would likely cause a buffer overflow
(this has not been tested or verified.)
CWE ID: CWE-369
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void mcryptd_check_internal(struct rtattr **tb, u32 *type,
u32 *mask)
{
struct crypto_attr_type *algt;
algt = crypto_get_attr_type(tb);
if (IS_ERR(algt))
return;
if ((algt->type & CRYPTO_ALG_INTERNAL))
*type |= CRYPTO_ALG_INTERNAL;
if ((algt->mask & CRYPTO_ALG_INTERNAL))
*mask |= CRYPTO_ALG_INTERNAL;
}
Commit Message: crypto: mcryptd - Check mcryptd algorithm compatibility
Algorithms not compatible with mcryptd could be spawned by mcryptd
with a direct crypto_alloc_tfm invocation using a "mcryptd(alg)" name
construct. This causes mcryptd to crash the kernel if an arbitrary
"alg" is incompatible and not intended to be used with mcryptd. It is
an issue if AF_ALG tries to spawn mcryptd(alg) to expose it externally.
But such algorithms must be used internally and not be exposed.
We added a check to enforce that only internal algorithms are allowed
with mcryptd at the time mcryptd is spawning an algorithm.
Link: http://marc.info/?l=linux-crypto-vger&m=148063683310477&w=2
Cc: [email protected]
Reported-by: Mikulas Patocka <[email protected]>
Signed-off-by: Tim Chen <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct sk_buff *nf_ct_frag6_gather(struct sk_buff *skb, u32 user)
{
struct sk_buff *clone;
struct net_device *dev = skb->dev;
struct frag_hdr *fhdr;
struct nf_ct_frag6_queue *fq;
struct ipv6hdr *hdr;
int fhoff, nhoff;
u8 prevhdr;
struct sk_buff *ret_skb = NULL;
/* Jumbo payload inhibits frag. header */
if (ipv6_hdr(skb)->payload_len == 0) {
pr_debug("payload len = 0\n");
return skb;
}
if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0)
return skb;
clone = skb_clone(skb, GFP_ATOMIC);
if (clone == NULL) {
pr_debug("Can't clone skb\n");
return skb;
}
NFCT_FRAG6_CB(clone)->orig = skb;
if (!pskb_may_pull(clone, fhoff + sizeof(*fhdr))) {
pr_debug("message is too short.\n");
goto ret_orig;
}
skb_set_transport_header(clone, fhoff);
hdr = ipv6_hdr(clone);
fhdr = (struct frag_hdr *)skb_transport_header(clone);
if (!(fhdr->frag_off & htons(0xFFF9))) {
pr_debug("Invalid fragment offset\n");
/* It is not a fragmented frame */
goto ret_orig;
}
if (atomic_read(&nf_init_frags.mem) > nf_init_frags.high_thresh)
nf_ct_frag6_evictor();
fq = fq_find(fhdr->identification, user, &hdr->saddr, &hdr->daddr);
if (fq == NULL) {
pr_debug("Can't find and can't create new queue\n");
goto ret_orig;
}
spin_lock_bh(&fq->q.lock);
if (nf_ct_frag6_queue(fq, clone, fhdr, nhoff) < 0) {
spin_unlock_bh(&fq->q.lock);
pr_debug("Can't insert skb to queue\n");
fq_put(fq);
goto ret_orig;
}
if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len) {
ret_skb = nf_ct_frag6_reasm(fq, dev);
if (ret_skb == NULL)
pr_debug("Can't reassemble fragmented packets\n");
}
spin_unlock_bh(&fq->q.lock);
fq_put(fq);
return ret_skb;
ret_orig:
kfree_skb(clone);
return skb;
}
Commit Message: netfilter: nf_conntrack_reasm: properly handle packets fragmented into a single fragment
When an ICMPV6_PKT_TOOBIG message is received with a MTU below 1280,
all further packets include a fragment header.
Unlike regular defragmentation, conntrack also needs to "reassemble"
those fragments in order to obtain a packet without the fragment
header for connection tracking. Currently nf_conntrack_reasm checks
whether a fragment has either IP6_MF set or an offset != 0, which
makes it ignore those fragments.
Remove the invalid check and make reassembly handle fragment queues
containing only a single fragment.
Reported-and-tested-by: Ulrich Weber <[email protected]>
Signed-off-by: Patrick McHardy <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static bool __init sparc64_has_md5_opcode(void)
{
unsigned long cfr;
if (!(sparc64_elf_hwcap & HWCAP_SPARC_CRYPTO))
return false;
__asm__ __volatile__("rd %%asr26, %0" : "=r" (cfr));
if (!(cfr & CFR_MD5))
return false;
return true;
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn)
{
enum direction dir = decode_direction(insn);
int size = decode_access_size(regs, insn);
int orig_asi, asi;
current_thread_info()->kern_una_regs = regs;
current_thread_info()->kern_una_insn = insn;
orig_asi = asi = decode_asi(insn, regs);
/* If this is a {get,put}_user() on an unaligned userspace pointer,
* just signal a fault and do not log the event.
*/
if (asi == ASI_AIUS) {
kernel_mna_trap_fault(0);
return;
}
log_unaligned(regs);
if (!ok_for_kernel(insn) || dir == both) {
printk("Unsupported unaligned load/store trap for kernel "
"at <%016lx>.\n", regs->tpc);
unaligned_panic("Kernel does fpu/atomic "
"unaligned load/store.", regs);
kernel_mna_trap_fault(0);
} else {
unsigned long addr, *reg_addr;
int err;
addr = compute_effective_address(regs, insn,
((insn >> 25) & 0x1f));
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr);
switch (asi) {
case ASI_NL:
case ASI_AIUPL:
case ASI_AIUSL:
case ASI_PL:
case ASI_SL:
case ASI_PNFL:
case ASI_SNFL:
asi &= ~0x08;
break;
}
switch (dir) {
case load:
reg_addr = fetch_reg_addr(((insn>>25)&0x1f), regs);
err = do_int_load(reg_addr, size,
(unsigned long *) addr,
decode_signedness(insn), asi);
if (likely(!err) && unlikely(asi != orig_asi)) {
unsigned long val_in = *reg_addr;
switch (size) {
case 2:
val_in = swab16(val_in);
break;
case 4:
val_in = swab32(val_in);
break;
case 8:
val_in = swab64(val_in);
break;
case 16:
default:
BUG();
break;
}
*reg_addr = val_in;
}
break;
case store:
err = do_int_store(((insn>>25)&0x1f), size,
(unsigned long *) addr, regs,
asi, orig_asi);
break;
default:
panic("Impossible kernel unaligned trap.");
/* Not reached... */
}
if (unlikely(err))
kernel_mna_trap_fault(1);
else
advance(regs);
}
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void php_snmp_error(zval *object, const char *docref, int type, const char *format, ...)
{
va_list args;
php_snmp_object *snmp_object = NULL;
if (object) {
snmp_object = Z_SNMP_P(object);
if (type == PHP_SNMP_ERRNO_NOERROR) {
memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr));
} else {
va_start(args, format);
vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args);
va_end(args);
}
snmp_object->snmp_errno = type;
}
if (type == PHP_SNMP_ERRNO_NOERROR) {
return;
}
if (object && (snmp_object->exceptions_enabled & type)) {
zend_throw_exception_ex(php_snmp_exception_ce, type, snmp_object->snmp_errstr);
} else {
va_start(args, format);
php_verror(docref, "", E_WARNING, format, args);
va_end(args);
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void __d_move(struct dentry *dentry, struct dentry *target,
bool exchange)
{
struct inode *dir = NULL;
unsigned n;
if (!dentry->d_inode)
printk(KERN_WARNING "VFS: moving negative dcache entry\n");
BUG_ON(d_ancestor(dentry, target));
BUG_ON(d_ancestor(target, dentry));
dentry_lock_for_move(dentry, target);
if (unlikely(d_in_lookup(target))) {
dir = target->d_parent->d_inode;
n = start_dir_add(dir);
__d_lookup_done(target);
}
write_seqcount_begin(&dentry->d_seq);
write_seqcount_begin_nested(&target->d_seq, DENTRY_D_LOCK_NESTED);
/* unhash both */
/* __d_drop does write_seqcount_barrier, but they're OK to nest. */
__d_drop(dentry);
__d_drop(target);
/* Switch the names.. */
if (exchange)
swap_names(dentry, target);
else
copy_name(dentry, target);
/* rehash in new place(s) */
__d_rehash(dentry);
if (exchange)
__d_rehash(target);
/* ... and switch them in the tree */
if (IS_ROOT(dentry)) {
/* splicing a tree */
dentry->d_flags |= DCACHE_RCUACCESS;
dentry->d_parent = target->d_parent;
target->d_parent = target;
list_del_init(&target->d_child);
list_move(&dentry->d_child, &dentry->d_parent->d_subdirs);
} else {
/* swapping two dentries */
swap(dentry->d_parent, target->d_parent);
list_move(&target->d_child, &target->d_parent->d_subdirs);
list_move(&dentry->d_child, &dentry->d_parent->d_subdirs);
if (exchange)
fsnotify_update_flags(target);
fsnotify_update_flags(dentry);
}
write_seqcount_end(&target->d_seq);
write_seqcount_end(&dentry->d_seq);
if (dir)
end_dir_add(dir, n);
dentry_unlock_for_move(dentry, target);
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc,
FT_Long* args )
{
FT_UInt num_axes = exc->face->blend->num_axis;
FT_Fixed* coords = exc->face->blend->normalizedcoords;
FT_UInt i;
if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) )
{
exc->error = FT_THROW( Stack_Overflow );
return;
}
for ( i = 0; i < num_axes; i++ )
args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */
}
Commit Message:
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
{
RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94
Target: 1
Example 2:
Code: int AutofillPopupBaseView::GetCornerRadius() {
return ChromeLayoutProvider::Get()->GetCornerRadiusMetric(
views::EMPHASIS_MEDIUM);
}
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 <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
{
struct rar *rar = (struct rar *)(a->format->data);
const void *h = __archive_read_ahead(a, min, avail);
int ret;
if (avail)
{
if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
*avail = a->archive.read_data_requested;
if (*avail > rar->bytes_remaining)
*avail = (ssize_t)rar->bytes_remaining;
if (*avail < 0)
return NULL;
else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
rar->file_flags & FHD_SPLIT_AFTER)
{
ret = archive_read_format_rar_read_header(a, a->entry);
if (ret == (ARCHIVE_EOF))
{
rar->has_endarc_header = 1;
ret = archive_read_format_rar_read_header(a, a->entry);
}
if (ret != (ARCHIVE_OK))
return NULL;
return rar_read_ahead(a, min, avail);
}
}
return h;
}
Commit Message: rar: file split across multi-part archives must match
Fuzzing uncovered some UAF and memory overrun bugs where a file in a
single file archive reported that it was split across multiple
volumes. This was caused by ppmd7 operations calling
rar_br_fillup. This would invoke rar_read_ahead, which would in some
situations invoke archive_read_format_rar_read_header. That would
check the new file name against the old file name, and if they didn't
match up it would free the ppmd7 buffer and allocate a new
one. However, because the ppmd7 decoder wasn't actually done with the
buffer, it would continue to used the freed buffer. Both reads and
writes to the freed region can be observed.
This is quite tricky to solve: once the buffer has been freed it is
too late, as the ppmd7 decoder functions almost universally assume
success - there's no way for ppmd_read to signal error, nor are there
good ways for functions like Range_Normalise to propagate them. So we
can't detect after the fact that we're in an invalid state - e.g. by
checking rar->cursor, we have to prevent ourselves from ever ending up
there. So, when we are in the dangerous part or rar_read_ahead that
assumes a valid split, we set a flag force read_header to either go
down the path for split files or bail. This means that the ppmd7
decoder keeps a valid buffer and just runs out of data.
Found with a combination of AFL, afl-rb and qsym.
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Extension::InitFromValue(const DictionaryValue& source, int flags,
std::string* error) {
URLPattern::ParseOption parse_strictness =
(flags & STRICT_ERROR_CHECKS ? URLPattern::ERROR_ON_PORTS
: URLPattern::IGNORE_PORTS);
permission_set_.reset(new ExtensionPermissionSet());
if (source.HasKey(keys::kPublicKey)) {
std::string public_key_bytes;
if (!source.GetString(keys::kPublicKey,
&public_key_) ||
!ParsePEMKeyBytes(public_key_,
&public_key_bytes) ||
!GenerateId(public_key_bytes, &id_)) {
*error = errors::kInvalidKey;
return false;
}
} else if (flags & REQUIRE_KEY) {
*error = errors::kInvalidKey;
return false;
} else {
id_ = Extension::GenerateIdForPath(path());
if (id_.empty()) {
NOTREACHED() << "Could not create ID from path.";
return false;
}
}
manifest_value_.reset(source.DeepCopy());
extension_url_ = Extension::GetBaseURLFromExtensionId(id());
std::string version_str;
if (!source.GetString(keys::kVersion, &version_str)) {
*error = errors::kInvalidVersion;
return false;
}
version_.reset(Version::GetVersionFromString(version_str));
if (!version_.get() ||
version_->components().size() > 4) {
*error = errors::kInvalidVersion;
return false;
}
string16 localized_name;
if (!source.GetString(keys::kName, &localized_name)) {
*error = errors::kInvalidName;
return false;
}
base::i18n::AdjustStringForLocaleDirection(&localized_name);
name_ = UTF16ToUTF8(localized_name);
if (source.HasKey(keys::kDescription)) {
if (!source.GetString(keys::kDescription,
&description_)) {
*error = errors::kInvalidDescription;
return false;
}
}
if (source.HasKey(keys::kHomepageURL)) {
std::string tmp;
if (!source.GetString(keys::kHomepageURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, "");
return false;
}
homepage_url_ = GURL(tmp);
if (!homepage_url_.is_valid() ||
(!homepage_url_.SchemeIs("http") &&
!homepage_url_.SchemeIs("https"))) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, tmp);
return false;
}
}
if (source.HasKey(keys::kUpdateURL)) {
std::string tmp;
if (!source.GetString(keys::kUpdateURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, "");
return false;
}
update_url_ = GURL(tmp);
if (!update_url_.is_valid() ||
update_url_.has_ref()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, tmp);
return false;
}
}
if (source.HasKey(keys::kMinimumChromeVersion)) {
std::string minimum_version_string;
if (!source.GetString(keys::kMinimumChromeVersion,
&minimum_version_string)) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
scoped_ptr<Version> minimum_version(
Version::GetVersionFromString(minimum_version_string));
if (!minimum_version.get()) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
chrome::VersionInfo current_version_info;
if (!current_version_info.is_valid()) {
NOTREACHED();
return false;
}
scoped_ptr<Version> current_version(
Version::GetVersionFromString(current_version_info.Version()));
if (!current_version.get()) {
DCHECK(false);
return false;
}
if (current_version->CompareTo(*minimum_version) < 0) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kChromeVersionTooLow,
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME),
minimum_version_string);
return false;
}
}
source.GetBoolean(keys::kConvertedFromUserScript,
&converted_from_user_script_);
if (source.HasKey(keys::kIcons)) {
DictionaryValue* icons_value = NULL;
if (!source.GetDictionary(keys::kIcons, &icons_value)) {
*error = errors::kInvalidIcons;
return false;
}
for (size_t i = 0; i < arraysize(kIconSizes); ++i) {
std::string key = base::IntToString(kIconSizes[i]);
if (icons_value->HasKey(key)) {
std::string icon_path;
if (!icons_value->GetString(key, &icon_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
if (!icon_path.empty() && icon_path[0] == '/')
icon_path = icon_path.substr(1);
if (icon_path.empty()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
icons_.Add(kIconSizes[i], icon_path);
}
}
}
is_theme_ = false;
if (source.HasKey(keys::kTheme)) {
if (ContainsNonThemeKeys(source)) {
*error = errors::kThemesCannotContainExtensions;
return false;
}
DictionaryValue* theme_value = NULL;
if (!source.GetDictionary(keys::kTheme, &theme_value)) {
*error = errors::kInvalidTheme;
return false;
}
is_theme_ = true;
DictionaryValue* images_value = NULL;
if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) {
for (DictionaryValue::key_iterator iter = images_value->begin_keys();
iter != images_value->end_keys(); ++iter) {
std::string val;
if (!images_value->GetString(*iter, &val)) {
*error = errors::kInvalidThemeImages;
return false;
}
}
theme_images_.reset(images_value->DeepCopy());
}
DictionaryValue* colors_value = NULL;
if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) {
for (DictionaryValue::key_iterator iter = colors_value->begin_keys();
iter != colors_value->end_keys(); ++iter) {
ListValue* color_list = NULL;
double alpha = 0.0;
int color = 0;
if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) ||
((color_list->GetSize() != 3) &&
((color_list->GetSize() != 4) ||
!color_list->GetDouble(3, &alpha))) ||
!color_list->GetInteger(0, &color) ||
!color_list->GetInteger(1, &color) ||
!color_list->GetInteger(2, &color)) {
*error = errors::kInvalidThemeColors;
return false;
}
}
theme_colors_.reset(colors_value->DeepCopy());
}
DictionaryValue* tints_value = NULL;
if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) {
for (DictionaryValue::key_iterator iter = tints_value->begin_keys();
iter != tints_value->end_keys(); ++iter) {
ListValue* tint_list = NULL;
double v = 0.0;
if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) ||
tint_list->GetSize() != 3 ||
!tint_list->GetDouble(0, &v) ||
!tint_list->GetDouble(1, &v) ||
!tint_list->GetDouble(2, &v)) {
*error = errors::kInvalidThemeTints;
return false;
}
}
theme_tints_.reset(tints_value->DeepCopy());
}
DictionaryValue* display_properties_value = NULL;
if (theme_value->GetDictionary(keys::kThemeDisplayProperties,
&display_properties_value)) {
theme_display_properties_.reset(
display_properties_value->DeepCopy());
}
return true;
}
if (source.HasKey(keys::kPlugins)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPlugins, &list_value)) {
*error = errors::kInvalidPlugins;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* plugin_value = NULL;
std::string path_str;
bool is_public = false;
if (!list_value->GetDictionary(i, &plugin_value)) {
*error = errors::kInvalidPlugins;
return false;
}
if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPath, base::IntToString(i));
return false;
}
if (plugin_value->HasKey(keys::kPluginsPublic)) {
if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPublic, base::IntToString(i));
return false;
}
}
#if !defined(OS_CHROMEOS)
plugins_.push_back(PluginInfo());
plugins_.back().path = path().AppendASCII(path_str);
plugins_.back().is_public = is_public;
#endif
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kNaClModules)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kNaClModules, &list_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* module_value = NULL;
std::string path_str;
std::string mime_type;
if (!list_value->GetDictionary(i, &module_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesPath, base::IntToString(i));
return false;
}
if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesMIMEType, base::IntToString(i));
return false;
}
nacl_modules_.push_back(NaClModuleInfo());
nacl_modules_.back().url = GetResourceURL(path_str);
nacl_modules_.back().mime_type = mime_type;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kToolstrips)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kToolstrips, &list_value)) {
*error = errors::kInvalidToolstrips;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
GURL toolstrip;
DictionaryValue* toolstrip_value = NULL;
std::string toolstrip_path;
if (list_value->GetString(i, &toolstrip_path)) {
toolstrip = GetResourceURL(toolstrip_path);
} else if (list_value->GetDictionary(i, &toolstrip_value)) {
if (!toolstrip_value->GetString(keys::kToolstripPath,
&toolstrip_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrip = GetResourceURL(toolstrip_path);
} else {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrips_.push_back(toolstrip);
}
}
if (source.HasKey(keys::kContentScripts)) {
ListValue* list_value;
if (!source.GetList(keys::kContentScripts, &list_value)) {
*error = errors::kInvalidContentScriptsList;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* content_script = NULL;
if (!list_value->GetDictionary(i, &content_script)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidContentScript, base::IntToString(i));
return false;
}
UserScript script;
if (!LoadUserScriptHelper(content_script, i, flags, error, &script))
return false; // Failed to parse script context definition.
script.set_extension_id(id());
if (converted_from_user_script_) {
script.set_emulate_greasemonkey(true);
script.set_match_all_frames(true); // Greasemonkey matches all frames.
}
content_scripts_.push_back(script);
}
}
DictionaryValue* page_action_value = NULL;
if (source.HasKey(keys::kPageActions)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPageActions, &list_value)) {
*error = errors::kInvalidPageActionsList;
return false;
}
size_t list_value_length = list_value->GetSize();
if (list_value_length == 0u) {
} else if (list_value_length == 1u) {
if (!list_value->GetDictionary(0, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
} else { // list_value_length > 1u.
*error = errors::kInvalidPageActionsListSize;
return false;
}
} else if (source.HasKey(keys::kPageAction)) {
if (!source.GetDictionary(keys::kPageAction, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
}
if (page_action_value) {
page_action_.reset(
LoadExtensionActionHelper(page_action_value, error));
if (!page_action_.get())
return false; // Failed to parse page action definition.
}
if (source.HasKey(keys::kBrowserAction)) {
DictionaryValue* browser_action_value = NULL;
if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) {
*error = errors::kInvalidBrowserAction;
return false;
}
browser_action_.reset(
LoadExtensionActionHelper(browser_action_value, error));
if (!browser_action_.get())
return false; // Failed to parse browser action definition.
}
if (source.HasKey(keys::kFileBrowserHandlers)) {
ListValue* file_browser_handlers_value = NULL;
if (!source.GetList(keys::kFileBrowserHandlers,
&file_browser_handlers_value)) {
*error = errors::kInvalidFileBrowserHandler;
return false;
}
file_browser_handlers_.reset(
LoadFileBrowserHandlers(file_browser_handlers_value, error));
if (!file_browser_handlers_.get())
return false; // Failed to parse file browser actions definition.
}
if (!LoadIsApp(manifest_value_.get(), error) ||
!LoadExtent(manifest_value_.get(), keys::kWebURLs,
&extent_,
errors::kInvalidWebURLs, errors::kInvalidWebURL,
parse_strictness, error) ||
!EnsureNotHybridApp(manifest_value_.get(), error) ||
!LoadLaunchURL(manifest_value_.get(), error) ||
!LoadLaunchContainer(manifest_value_.get(), error) ||
!LoadAppIsolation(manifest_value_.get(), error)) {
return false;
}
if (source.HasKey(keys::kOptionsPage)) {
std::string options_str;
if (!source.GetString(keys::kOptionsPage, &options_str)) {
*error = errors::kInvalidOptionsPage;
return false;
}
if (is_hosted_app()) {
GURL options_url(options_str);
if (!options_url.is_valid() ||
!(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) {
*error = errors::kInvalidOptionsPageInHostedApp;
return false;
}
options_url_ = options_url;
} else {
GURL absolute(options_str);
if (absolute.is_valid()) {
*error = errors::kInvalidOptionsPageExpectUrlInPackage;
return false;
}
options_url_ = GetResourceURL(options_str);
if (!options_url_.is_valid()) {
*error = errors::kInvalidOptionsPage;
return false;
}
}
}
ExtensionAPIPermissionSet api_permissions;
URLPatternSet host_permissions;
if (source.HasKey(keys::kPermissions)) {
ListValue* permissions = NULL;
if (!source.GetList(keys::kPermissions, &permissions)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissions, "");
return false;
}
for (size_t i = 0; i < permissions->GetSize(); ++i) {
std::string permission_str;
if (!permissions->GetString(i, &permission_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermission, base::IntToString(i));
return false;
}
ExtensionAPIPermission* permission =
ExtensionPermissionsInfo::GetInstance()->GetByName(permission_str);
if (!IsComponentOnlyPermission(permission)
#ifndef NDEBUG
&& !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExposePrivateExtensionApi)
#endif
) {
continue;
}
if (web_extent().is_empty() || location() == Extension::COMPONENT) {
if (permission != NULL) {
if (IsDisallowedExperimentalPermission(permission->id()) &&
location() != Extension::COMPONENT) {
*error = errors::kExperimentalFlagRequired;
return false;
}
api_permissions.insert(permission->id());
continue;
}
} else {
if (permission != NULL && permission->is_hosted_app()) {
if (IsDisallowedExperimentalPermission(permission->id())) {
*error = errors::kExperimentalFlagRequired;
return false;
}
api_permissions.insert(permission->id());
continue;
}
}
URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ?
URLPattern::SCHEME_ALL : kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = pattern.Parse(permission_str,
parse_strictness);
if (parse_result == URLPattern::PARSE_SUCCESS) {
if (!CanSpecifyHostPermission(pattern)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissionScheme, base::IntToString(i));
return false;
}
pattern.SetPath("/*");
if (pattern.MatchesScheme(chrome::kFileScheme) &&
!CanExecuteScriptEverywhere()) {
wants_file_access_ = true;
if (!(flags & ALLOW_FILE_ACCESS))
pattern.set_valid_schemes(
pattern.valid_schemes() & ~URLPattern::SCHEME_FILE);
}
host_permissions.AddPattern(pattern);
}
}
}
if (source.HasKey(keys::kBackground)) {
std::string background_str;
if (!source.GetString(keys::kBackground, &background_str)) {
*error = errors::kInvalidBackground;
return false;
}
if (is_hosted_app()) {
if (!api_permissions.count(ExtensionAPIPermission::kBackground)) {
*error = errors::kBackgroundPermissionNeeded;
return false;
}
GURL bg_page(background_str);
if (!bg_page.is_valid()) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
if (!(bg_page.SchemeIs("https") ||
(CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAllowHTTPBackgroundPage) &&
bg_page.SchemeIs("http")))) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
background_url_ = bg_page;
} else {
background_url_ = GetResourceURL(background_str);
}
}
if (source.HasKey(keys::kDefaultLocale)) {
if (!source.GetString(keys::kDefaultLocale, &default_locale_) ||
!l10n_util::IsValidLocaleSyntax(default_locale_)) {
*error = errors::kInvalidDefaultLocale;
return false;
}
}
if (source.HasKey(keys::kChromeURLOverrides)) {
DictionaryValue* overrides = NULL;
if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
for (DictionaryValue::key_iterator iter = overrides->begin_keys();
iter != overrides->end_keys(); ++iter) {
std::string page = *iter;
std::string val;
if ((page != chrome::kChromeUINewTabHost &&
#if defined(TOUCH_UI)
page != chrome::kChromeUIKeyboardHost &&
#endif
#if defined(OS_CHROMEOS)
page != chrome::kChromeUIActivationMessageHost &&
#endif
page != chrome::kChromeUIBookmarksHost &&
page != chrome::kChromeUIHistoryHost) ||
!overrides->GetStringWithoutPathExpansion(*iter, &val)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
chrome_url_overrides_[page] = GetResourceURL(val);
}
if (overrides->size() > 1) {
*error = errors::kMultipleOverrides;
return false;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kInputComponents)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kInputComponents, &list_value)) {
*error = errors::kInvalidInputComponents;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* module_value = NULL;
std::string name_str;
InputComponentType type;
std::string id_str;
std::string description_str;
std::string language_str;
std::set<std::string> layouts;
std::string shortcut_keycode_str;
bool shortcut_alt = false;
bool shortcut_ctrl = false;
bool shortcut_shift = false;
if (!list_value->GetDictionary(i, &module_value)) {
*error = errors::kInvalidInputComponents;
return false;
}
if (!module_value->GetString(keys::kName, &name_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentName, base::IntToString(i));
return false;
}
std::string type_str;
if (module_value->GetString(keys::kType, &type_str)) {
if (type_str == "ime") {
type = INPUT_COMPONENT_TYPE_IME;
} else if (type_str == "virtual_keyboard") {
type = INPUT_COMPONENT_TYPE_VIRTUAL_KEYBOARD;
} else {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentType, base::IntToString(i));
return false;
}
} else {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentType, base::IntToString(i));
return false;
}
if (!module_value->GetString(keys::kId, &id_str)) {
id_str = "";
}
if (!module_value->GetString(keys::kDescription, &description_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentDescription, base::IntToString(i));
return false;
}
if (!module_value->GetString(keys::kLanguage, &language_str)) {
language_str = "";
}
ListValue* layouts_value = NULL;
if (!module_value->GetList(keys::kLayouts, &layouts_value)) {
*error = errors::kInvalidInputComponentLayouts;
return false;
}
for (size_t j = 0; j < layouts_value->GetSize(); ++j) {
std::string layout_name_str;
if (!layouts_value->GetString(j, &layout_name_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentLayoutName, base::IntToString(i),
base::IntToString(j));
return false;
}
layouts.insert(layout_name_str);
}
if (module_value->HasKey(keys::kShortcutKey)) {
DictionaryValue* shortcut_value = NULL;
if (!module_value->GetDictionary(keys::kShortcutKey, &shortcut_value)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentShortcutKey, base::IntToString(i));
return false;
}
if (!shortcut_value->GetString(keys::kKeycode, &shortcut_keycode_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidInputComponentShortcutKeycode,
base::IntToString(i));
return false;
}
if (!shortcut_value->GetBoolean(keys::kAltKey, &shortcut_alt)) {
shortcut_alt = false;
}
if (!shortcut_value->GetBoolean(keys::kCtrlKey, &shortcut_ctrl)) {
shortcut_ctrl = false;
}
if (!shortcut_value->GetBoolean(keys::kShiftKey, &shortcut_shift)) {
shortcut_shift = false;
}
}
input_components_.push_back(InputComponentInfo());
input_components_.back().name = name_str;
input_components_.back().type = type;
input_components_.back().id = id_str;
input_components_.back().description = description_str;
input_components_.back().language = language_str;
input_components_.back().layouts.insert(layouts.begin(), layouts.end());
input_components_.back().shortcut_keycode = shortcut_keycode_str;
input_components_.back().shortcut_alt = shortcut_alt;
input_components_.back().shortcut_ctrl = shortcut_ctrl;
input_components_.back().shortcut_shift = shortcut_shift;
}
}
if (source.HasKey(keys::kOmnibox)) {
if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) ||
omnibox_keyword_.empty()) {
*error = errors::kInvalidOmniboxKeyword;
return false;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kContentSecurityPolicy)) {
std::string content_security_policy;
if (!source.GetString(keys::kContentSecurityPolicy,
&content_security_policy)) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
const char kBadCSPCharacters[] = {'\r', '\n', '\0'};
if (content_security_policy.find_first_of(kBadCSPCharacters, 0,
arraysize(kBadCSPCharacters)) !=
std::string::npos) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
content_security_policy_ = content_security_policy;
}
if (source.HasKey(keys::kDevToolsPage)) {
std::string devtools_str;
if (!source.GetString(keys::kDevToolsPage, &devtools_str)) {
*error = errors::kInvalidDevToolsPage;
return false;
}
if (!api_permissions.count(ExtensionAPIPermission::kExperimental)) {
*error = errors::kDevToolsExperimental;
return false;
}
devtools_url_ = GetResourceURL(devtools_str);
}
if (source.HasKey(keys::kSidebar)) {
DictionaryValue* sidebar_value = NULL;
if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) {
*error = errors::kInvalidSidebar;
return false;
}
if (!api_permissions.count(ExtensionAPIPermission::kExperimental)) {
*error = errors::kSidebarExperimental;
return false;
}
sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error));
if (!sidebar_defaults_.get())
return false; // Failed to parse sidebar definition.
}
if (source.HasKey(keys::kTts)) {
DictionaryValue* tts_dict = NULL;
if (!source.GetDictionary(keys::kTts, &tts_dict)) {
*error = errors::kInvalidTts;
return false;
}
if (tts_dict->HasKey(keys::kTtsVoices)) {
ListValue* tts_voices = NULL;
if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) {
*error = errors::kInvalidTtsVoices;
return false;
}
for (size_t i = 0; i < tts_voices->GetSize(); i++) {
DictionaryValue* one_tts_voice = NULL;
if (!tts_voices->GetDictionary(i, &one_tts_voice)) {
*error = errors::kInvalidTtsVoices;
return false;
}
TtsVoice voice_data;
if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesVoiceName, &voice_data.voice_name)) {
*error = errors::kInvalidTtsVoicesVoiceName;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesLocale, &voice_data.locale) ||
!l10n_util::IsValidLocaleSyntax(voice_data.locale)) {
*error = errors::kInvalidTtsVoicesLocale;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesGender, &voice_data.gender) ||
(voice_data.gender != keys::kTtsGenderMale &&
voice_data.gender != keys::kTtsGenderFemale)) {
*error = errors::kInvalidTtsVoicesGender;
return false;
}
}
tts_voices_.push_back(voice_data);
}
}
}
incognito_split_mode_ = is_app();
if (source.HasKey(keys::kIncognito)) {
std::string value;
if (!source.GetString(keys::kIncognito, &value)) {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
if (value == values::kIncognitoSpanning) {
incognito_split_mode_ = false;
} else if (value == values::kIncognitoSplit) {
incognito_split_mode_ = true;
} else {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
}
if (HasMultipleUISurfaces()) {
*error = errors::kOneUISurfaceOnly;
return false;
}
permission_set_.reset(
new ExtensionPermissionSet(this, api_permissions, host_permissions));
DCHECK(source.Equals(manifest_value_.get()));
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: static v8::Handle<v8::Value> OpenChannelToTab(const v8::Arguments& args) {
RenderView* renderview = bindings_utils::GetRenderViewForCurrentContext();
if (!renderview)
return v8::Undefined();
if (args.Length() >= 3 && args[0]->IsInt32() && args[1]->IsString() &&
args[2]->IsString()) {
int tab_id = args[0]->Int32Value();
std::string extension_id = *v8::String::Utf8Value(args[1]->ToString());
std::string channel_name = *v8::String::Utf8Value(args[2]->ToString());
int port_id = -1;
renderview->Send(new ExtensionHostMsg_OpenChannelToTab(
renderview->routing_id(), tab_id, extension_id, channel_name,
&port_id));
return v8::Integer::New(port_id);
}
return v8::Undefined();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int strdup_if_nonnull(char **target, char *source)
{
if (source) {
*target = kstrdup(source, GFP_KERNEL);
if (!*target)
return -ENOMEM;
} else
*target = NULL;
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
ptr++; /* skip "Reserved" */
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static __poll_t fuse_dev_poll(struct file *file, poll_table *wait)
{
__poll_t mask = EPOLLOUT | EPOLLWRNORM;
struct fuse_iqueue *fiq;
struct fuse_dev *fud = fuse_get_dev(file);
if (!fud)
return EPOLLERR;
fiq = &fud->fc->iq;
poll_wait(file, &fiq->waitq, wait);
spin_lock(&fiq->waitq.lock);
if (!fiq->connected)
mask = EPOLLERR;
else if (request_pending(fiq))
mask |= EPOLLIN | EPOLLRDNORM;
spin_unlock(&fiq->waitq.lock);
return mask;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ)
{
krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH;
char **realms, **cpp, *temp_buf=NULL;
krb5_data *comp1 = NULL, *comp2 = NULL;
char *comp1_str = NULL;
/* By now we know that server principal name is unknown.
* If CANONICALIZE flag is set in the request
* If req is not U2U authn. req
* the requested server princ. has exactly two components
* either
* the name type is NT-SRV-HST
* or name type is NT-UNKNOWN and
* the 1st component is listed in conf file under host_based_services
* the 1st component is not in a list in conf under "no_host_referral"
* the 2d component looks like fully-qualified domain name (FQDN)
* If all of these conditions are satisfied - try mapping the FQDN and
* re-process the request as if client had asked for cross-realm TGT.
*/
if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) &&
!isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) &&
krb5_princ_size(kdc_context, request->server) == 2) {
comp1 = krb5_princ_component(kdc_context, request->server, 0);
comp2 = krb5_princ_component(kdc_context, request->server, 1);
comp1_str = calloc(1,comp1->length+1);
if (!comp1_str) {
retval = ENOMEM;
goto cleanup;
}
strlcpy(comp1_str,comp1->data,comp1->length+1);
if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST ||
krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST ||
(krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN &&
kdc_active_realm->realm_host_based_services != NULL &&
(krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,
comp1_str) == TRUE ||
krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,
KRB5_CONF_ASTERISK) == TRUE))) &&
(kdc_active_realm->realm_no_host_referral == NULL ||
(krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,
KRB5_CONF_ASTERISK) == FALSE &&
krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,
comp1_str) == FALSE))) {
if (memchr(comp2->data, '.', comp2->length) == NULL)
goto cleanup;
temp_buf = calloc(1, comp2->length+1);
if (!temp_buf) {
retval = ENOMEM;
goto cleanup;
}
strlcpy(temp_buf, comp2->data,comp2->length+1);
retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms);
free(temp_buf);
if (retval) {
/* no match found */
kdc_err(kdc_context, retval, "unable to find realm of host");
goto cleanup;
}
if (realms == 0) {
retval = KRB5KRB_AP_ERR_BADMATCH;
goto cleanup;
}
/* Don't return a referral to the null realm or the service
* realm. */
if (realms[0] == 0 ||
data_eq_string(request->server->realm, realms[0])) {
free(realms[0]);
free(realms);
retval = KRB5KRB_AP_ERR_BADMATCH;
goto cleanup;
}
/* Modify request.
* Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM
* and use it as a principal in this req.
*/
retval = krb5_build_principal(kdc_context, krbtgt_princ,
(*request->server).realm.length,
(*request->server).realm.data,
"krbtgt", realms[0], (char *)0);
for (cpp = realms; *cpp; cpp++)
free(*cpp);
}
}
cleanup:
free(comp1_str);
return retval;
}
Commit Message: KDC TGS-REQ null deref [CVE-2013-1416]
By sending an unusual but valid TGS-REQ, an authenticated remote
attacker can cause the KDC process to crash by dereferencing a null
pointer.
prep_reprocess_req() can cause a null pointer dereference when
processing a service principal name. Code in this function can
inappropriately pass a null pointer to strlcpy(). Unmodified client
software can trivially trigger this vulnerability, but the attacker
must have already authenticated and received a valid Kerberos ticket.
The vulnerable code was introduced by the implementation of new
service principal realm referral functionality in krb5-1.7, but was
corrected as a side effect of the KDC refactoring in krb5-1.11.
CVSSv2 vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:H/RL:O/RC:C
ticket: 7600 (new)
version_fixed: 1.10.5
status: resolved
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PaymentRequest::Abort() {
bool accepting_abort = !state_->IsPaymentAppInvoked();
if (accepting_abort)
RecordFirstAbortReason(JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT);
if (client_.is_bound())
client_->OnAbort(accepting_abort);
if (observer_for_testing_)
observer_for_testing_->OnAbortCalled();
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189
Target: 1
Example 2:
Code: struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
struct mem_cgroup *memcg)
{
struct mem_cgroup_per_zone *mz;
if (mem_cgroup_disabled())
return &zone->lruvec;
mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
return &mz->lruvec;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TaskManagerView::Init() {
table_model_.reset(new TaskManagerTableModel(model_));
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN,
ui::TableColumn::LEFT, -1, 1));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN,
ui::TableColumn::LEFT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(
ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
tab_table_ = new BackgroundColorGroupTableView(
table_model_.get(), columns_, highlight_background_resources_);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
false);
tab_table_->SetColumnVisibility(
IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN,
false);
UpdateStatsCounters();
tab_table_->SetObserver(this);
tab_table_->set_context_menu_controller(this);
set_context_menu_controller(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPurgeMemoryButton)) {
purge_memory_button_ = new views::NativeTextButton(this,
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY));
}
kill_button_ = new views::NativeTextButton(
this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL));
kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, false, false,
false));
kill_button_->SetAccessibleKeyboardShortcut(L"E");
kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW);
about_memory_link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK));
about_memory_link_->set_listener(this);
OnSelectionChanged();
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DefragVlanQinQTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 1;
p1->vlan_id[1] = 1;
p2->vlan_id[1] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
Target: 1
Example 2:
Code: static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt)
{
if (cmpt->stream_) {
jas_stream_close(cmpt->stream_);
}
jas_free(cmpt);
}
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
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static unsigned short len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
}
Commit Message: Fix double-free/OOB-write while receiving IPC data
If a malicious client pretends to be the E17 window manager, it is
possible to trigger an out of boundary heap write while receiving an
IPC message.
The length of the already received message is stored in an unsigned
short, which overflows after receiving 64 KB of data. It's comparably
small amount of data and therefore achievable for an attacker.
When len overflows, realloc() will either be called with a small value
and therefore chars will be appended out of bounds, or len + 1 will be
exactly 0, in which case realloc() behaves like free(). This could be
abused for a later double-free attack as it's even possible to overwrite
the free information -- but this depends on the malloc implementation.
Signed-off-by: Tobias Stoeckmann <[email protected]>
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const chromeos::InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void enl_ipc_send(char *str)
{
static char *last_msg = NULL;
char buff[21];
register unsigned short i;
register unsigned char j;
unsigned short len;
XEvent ev;
if (str == NULL) {
if (last_msg == NULL)
eprintf("eeek");
str = last_msg;
D(("Resending last message \"%s\" to Enlightenment.\n", str));
} else {
if (last_msg != NULL) {
free(last_msg);
}
last_msg = estrdup(str);
D(("Sending \"%s\" to Enlightenment.\n", str));
}
if (ipc_win == None) {
if ((ipc_win = enl_ipc_get_win()) == None) {
D(("Hrm. Enlightenment doesn't seem to be running. No IPC window, no IPC.\n"));
return;
}
}
len = strlen(str);
ipc_atom = XInternAtom(disp, "ENL_MSG", False);
if (ipc_atom == None) {
D(("IPC error: Unable to find/create ENL_MSG atom.\n"));
return;
}
for (; XCheckTypedWindowEvent(disp, my_ipc_win, ClientMessage, &ev);); /* Discard any out-of-sync messages */
ev.xclient.type = ClientMessage;
ev.xclient.serial = 0;
ev.xclient.send_event = True;
ev.xclient.window = ipc_win;
ev.xclient.message_type = ipc_atom;
ev.xclient.format = 8;
for (i = 0; i < len + 1; i += 12) {
sprintf(buff, "%8x", (int) my_ipc_win);
for (j = 0; j < 12; j++) {
buff[8 + j] = str[i + j];
if (!str[i + j]) {
break;
}
}
buff[20] = 0;
for (j = 0; j < 20; j++) {
ev.xclient.data.b[j] = buff[j];
}
XSendEvent(disp, ipc_win, False, 0, (XEvent *) & ev);
}
return;
}
Commit Message: Fix double-free/OOB-write while receiving IPC data
If a malicious client pretends to be the E17 window manager, it is
possible to trigger an out of boundary heap write while receiving an
IPC message.
The length of the already received message is stored in an unsigned
short, which overflows after receiving 64 KB of data. It's comparably
small amount of data and therefore achievable for an attacker.
When len overflows, realloc() will either be called with a small value
and therefore chars will be appended out of bounds, or len + 1 will be
exactly 0, in which case realloc() behaves like free(). This could be
abused for a later double-free attack as it's even possible to overwrite
the free information -- but this depends on the malloc implementation.
Signed-off-by: Tobias Stoeckmann <[email protected]>
CWE ID: CWE-787
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
bool is_new_navigation) {
DocumentState* document_state =
DocumentState::FromDataSource(frame->dataSource());
NavigationState* navigation_state = document_state->navigation_state();
if (document_state->commit_load_time().is_null())
document_state->set_commit_load_time(Time::Now());
if (is_new_navigation) {
UpdateSessionHistory(frame);
page_id_ = next_page_id_++;
if (GetLoadingUrl(frame) != GURL("about:swappedout")) {
history_list_offset_++;
if (history_list_offset_ >= content::kMaxSessionHistoryEntries)
history_list_offset_ = content::kMaxSessionHistoryEntries - 1;
history_list_length_ = history_list_offset_ + 1;
history_page_ids_.resize(history_list_length_, -1);
history_page_ids_[history_list_offset_] = page_id_;
}
} else {
if (navigation_state->pending_page_id() != -1 &&
navigation_state->pending_page_id() != page_id_ &&
!navigation_state->request_committed()) {
UpdateSessionHistory(frame);
page_id_ = navigation_state->pending_page_id();
history_list_offset_ = navigation_state->pending_history_list_offset();
DCHECK(history_list_length_ <= 0 ||
history_list_offset_ < 0 ||
history_list_offset_ >= history_list_length_ ||
history_page_ids_[history_list_offset_] == page_id_);
}
}
FOR_EACH_OBSERVER(RenderViewObserver, observers_,
DidCommitProvisionalLoad(frame, is_new_navigation));
navigation_state->set_request_committed(true);
UpdateURL(frame);
completed_client_redirect_src_ = Referrer();
UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int rds_loop_xmit(struct rds_connection *conn, struct rds_message *rm,
unsigned int hdr_off, unsigned int sg,
unsigned int off)
{
/* Do not send cong updates to loopback */
if (rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) {
rds_cong_map_updated(conn->c_fcong, ~(u64) 0);
return sizeof(struct rds_header) + RDS_CONG_MAP_BYTES;
}
BUG_ON(hdr_off || sg || off);
rds_inc_init(&rm->m_inc, conn, conn->c_laddr);
/* For the embedded inc. Matching put is in loop_inc_free() */
rds_message_addref(rm);
rds_recv_incoming(conn, conn->c_laddr, conn->c_faddr, &rm->m_inc,
GFP_KERNEL, KM_USER0);
rds_send_drop_acked(conn, be64_to_cpu(rm->m_inc.i_hdr.h_sequence),
NULL);
rds_inc_put(&rm->m_inc);
return sizeof(struct rds_header) + be32_to_cpu(rm->m_inc.i_hdr.h_len);
}
Commit Message: rds: prevent BUG_ON triggering on congestion map updates
Recently had this bug halt reported to me:
kernel BUG at net/rds/send.c:329!
Oops: Exception in kernel mode, sig: 5 [#1]
SMP NR_CPUS=1024 NUMA pSeries
Modules linked in: rds sunrpc ipv6 dm_mirror dm_region_hash dm_log ibmveth sg
ext4 jbd2 mbcache sd_mod crc_t10dif ibmvscsic scsi_transport_srp scsi_tgt
dm_mod [last unloaded: scsi_wait_scan]
NIP: d000000003ca68f4 LR: d000000003ca67fc CTR: d000000003ca8770
REGS: c000000175cab980 TRAP: 0700 Not tainted (2.6.32-118.el6.ppc64)
MSR: 8000000000029032 <EE,ME,CE,IR,DR> CR: 44000022 XER: 00000000
TASK = c00000017586ec90[1896] 'krdsd' THREAD: c000000175ca8000 CPU: 0
GPR00: 0000000000000150 c000000175cabc00 d000000003cb7340 0000000000002030
GPR04: ffffffffffffffff 0000000000000030 0000000000000000 0000000000000030
GPR08: 0000000000000001 0000000000000001 c0000001756b1e30 0000000000010000
GPR12: d000000003caac90 c000000000fa2500 c0000001742b2858 c0000001742b2a00
GPR16: c0000001742b2a08 c0000001742b2820 0000000000000001 0000000000000001
GPR20: 0000000000000040 c0000001742b2814 c000000175cabc70 0800000000000000
GPR24: 0000000000000004 0200000000000000 0000000000000000 c0000001742b2860
GPR28: 0000000000000000 c0000001756b1c80 d000000003cb68e8 c0000001742b27b8
NIP [d000000003ca68f4] .rds_send_xmit+0x4c4/0x8a0 [rds]
LR [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds]
Call Trace:
[c000000175cabc00] [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds]
(unreliable)
[c000000175cabd30] [d000000003ca7e64] .rds_send_worker+0x54/0x100 [rds]
[c000000175cabdb0] [c0000000000b475c] .worker_thread+0x1dc/0x3c0
[c000000175cabed0] [c0000000000baa9c] .kthread+0xbc/0xd0
[c000000175cabf90] [c000000000032114] .kernel_thread+0x54/0x70
Instruction dump:
4bfffd50 60000000 60000000 39080001 935f004c f91f0040 41820024 813d017c
7d094a78 7d290074 7929d182 394a0020 <0b090000> 40e2ff68 4bffffa4 39200000
Kernel panic - not syncing: Fatal exception
Call Trace:
[c000000175cab560] [c000000000012e04] .show_stack+0x74/0x1c0 (unreliable)
[c000000175cab610] [c0000000005a365c] .panic+0x80/0x1b4
[c000000175cab6a0] [c00000000002fbcc] .die+0x21c/0x2a0
[c000000175cab750] [c000000000030000] ._exception+0x110/0x220
[c000000175cab910] [c000000000004b9c] program_check_common+0x11c/0x180
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: JsVar *jsvArrayPopFirst(JsVar *arr) {
assert(jsvIsArray(arr));
if (jsvGetFirstChild(arr)) {
JsVar *child = jsvLock(jsvGetFirstChild(arr));
if (jsvGetFirstChild(arr) == jsvGetLastChild(arr))
jsvSetLastChild(arr, 0); // if 1 item in array
jsvSetFirstChild(arr, jsvGetNextSibling(child)); // unlink from end of array
jsvUnRef(child); // as no longer in array
if (jsvGetNextSibling(child)) {
JsVar *v = jsvLock(jsvGetNextSibling(child));
jsvSetPrevSibling(v, 0);
jsvUnLock(v);
}
jsvSetNextSibling(child, 0);
return child; // and return it
} else {
return 0;
}
}
Commit Message: fix jsvGetString regression
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::string TestURLLoader::TestFailsBogusContentLength() {
pp::URLRequestInfo request(instance_);
request.SetURL("/echo");
request.SetMethod("POST");
request.SetHeaders("Content-Length: 400");
std::string postdata("postdata");
request.AppendDataToBody(postdata.data(),
static_cast<uint32_t>(postdata.length()));
int32_t rv;
rv = OpenUntrusted(request, NULL);
if (rv != PP_ERROR_NOACCESS)
return ReportError(
"Untrusted request with bogus Content-Length restriction", rv);
PASS();
}
Commit Message: Fix one implicit 64-bit -> 32-bit implicit conversion in a PPAPI test.
../../ppapi/tests/test_url_loader.cc:877:11: warning: implicit conversion loses integer precision: 'int64_t' (aka 'long long') to 'int32_t' (aka 'int') [-Wshorten-64-to-32]
total_bytes_to_be_received);
^~~~~~~~~~~~~~~~~~~~~~~~~~
BUG=879657
Change-Id: I152f456368131fe7a2891ff0c97bf83f26ef0906
Reviewed-on: https://chromium-review.googlesource.com/c/1220173
Commit-Queue: Raymes Khoury <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600182}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetNotificationImageSizes",
base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID:
Target: 1
Example 2:
Code: void FreePixmap(Display* display, XID pixmap) {
XFreePixmap(display, pixmap);
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: ...
CWE ID: CWE-772
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GDataFileSystem::AddUploadedFileOnUIThread(
UploadMode upload_mode,
const FilePath& virtual_dir_path,
scoped_ptr<DocumentEntry> entry,
const FilePath& file_content_path,
GDataCache::FileOperationType cache_operation,
const base::Closure& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::ScopedClosureRunner callback_runner(callback);
if (!entry.get()) {
NOTREACHED();
return;
}
GDataEntry* dir_entry = directory_service_->FindEntryByPathSync(
virtual_dir_path);
if (!dir_entry)
return;
GDataDirectory* parent_dir = dir_entry->AsGDataDirectory();
if (!parent_dir)
return;
scoped_ptr<GDataEntry> new_entry(
GDataEntry::FromDocumentEntry(
NULL, entry.get(), directory_service_.get()));
if (!new_entry.get())
return;
if (upload_mode == UPLOAD_EXISTING_FILE) {
const std::string& resource_id = new_entry->resource_id();
directory_service_->GetEntryByResourceIdAsync(resource_id,
base::Bind(&RemoveStaleEntryOnUpload, resource_id, parent_dir));
}
GDataFile* file = new_entry->AsGDataFile();
DCHECK(file);
const std::string& resource_id = file->resource_id();
const std::string& md5 = file->file_md5();
parent_dir->AddEntry(new_entry.release());
OnDirectoryChanged(virtual_dir_path);
if (upload_mode == UPLOAD_NEW_FILE) {
cache_->StoreOnUIThread(resource_id,
md5,
file_content_path,
cache_operation,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else if (upload_mode == UPLOAD_EXISTING_FILE) {
cache_->ClearDirtyOnUIThread(resource_id,
md5,
base::Bind(&OnCacheUpdatedForAddUploadedFile,
callback_runner.Release()));
} else {
NOTREACHED() << "Unexpected upload mode: " << upload_mode;
}
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: ssize_t Camera3Device::getPointCloudBufferSize() const {
const int FLOATS_PER_POINT=4;
camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
if (maxPointCount.count == 0) {
ALOGE("%s: Camera %d: Can't find maximum depth point cloud size in static metadata!",
__FUNCTION__, mId);
return BAD_VALUE;
}
ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
return maxBytesForPointCloud;
}
Commit Message: Camera3Device: Validate template ID
Validate template ID before creating a default request.
Bug: 26866110
Bug: 27568958
Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d
CWE ID: CWE-264
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: NavigationRequest::NavigationRequest(
FrameTreeNode* frame_tree_node,
const CommonNavigationParams& common_params,
mojom::BeginNavigationParamsPtr begin_params,
const CommitNavigationParams& commit_params,
bool browser_initiated,
bool from_begin_navigation,
bool is_for_commit,
const FrameNavigationEntry* frame_entry,
NavigationEntryImpl* entry,
std::unique_ptr<NavigationUIData> navigation_ui_data,
mojom::NavigationClientAssociatedPtrInfo navigation_client,
blink::mojom::NavigationInitiatorPtr navigation_initiator)
: frame_tree_node_(frame_tree_node),
common_params_(common_params),
begin_params_(std::move(begin_params)),
commit_params_(commit_params),
browser_initiated_(browser_initiated),
navigation_ui_data_(std::move(navigation_ui_data)),
state_(NOT_STARTED),
restore_type_(RestoreType::NONE),
is_view_source_(false),
bindings_(NavigationEntryImpl::kInvalidBindings),
response_should_be_rendered_(true),
associated_site_instance_type_(AssociatedSiteInstanceType::NONE),
from_begin_navigation_(from_begin_navigation),
has_stale_copy_in_cache_(false),
net_error_(net::OK),
devtools_navigation_token_(base::UnguessableToken::Create()),
request_navigation_client_(nullptr),
commit_navigation_client_(nullptr),
weak_factory_(this) {
DCHECK(!browser_initiated || (entry != nullptr && frame_entry != nullptr));
DCHECK(!IsRendererDebugURL(common_params_.url));
DCHECK(common_params_.method == "POST" || !common_params_.post_data);
TRACE_EVENT_ASYNC_BEGIN2("navigation", "NavigationRequest", this,
"frame_tree_node",
frame_tree_node_->frame_tree_node_id(), "url",
common_params_.url.possibly_invalid_spec());
common_params_.referrer =
Referrer::SanitizeForRequest(common_params_.url, common_params_.referrer);
if (from_begin_navigation_) {
source_site_instance_ =
frame_tree_node->current_frame_host()->GetSiteInstance();
if (IsPerNavigationMojoInterfaceEnabled()) {
DCHECK(navigation_client.is_valid());
request_navigation_client_ = mojom::NavigationClientAssociatedPtr();
request_navigation_client_.Bind(std::move(navigation_client));
HandleInterfaceDisconnection(
&request_navigation_client_,
base::BindOnce(&NavigationRequest::OnRendererAbortedNavigation,
base::Unretained(this)));
associated_site_instance_id_ = source_site_instance_->GetId();
}
} else if (entry) {
DCHECK(!navigation_client.is_valid());
FrameNavigationEntry* frame_navigation_entry =
entry->GetFrameEntry(frame_tree_node);
if (frame_navigation_entry) {
source_site_instance_ = frame_navigation_entry->source_site_instance();
dest_site_instance_ = frame_navigation_entry->site_instance();
}
restore_type_ = entry->restore_type();
is_view_source_ = entry->IsViewSourceMode();
bindings_ = entry->bindings();
}
UpdateLoadFlagsWithCacheFlags(&begin_params_->load_flags,
common_params_.navigation_type,
common_params_.method == "POST");
if (entry)
nav_entry_id_ = entry->GetUniqueID();
std::string user_agent_override;
if (commit_params.is_overriding_user_agent ||
(entry && entry->GetIsOverridingUserAgent())) {
user_agent_override =
frame_tree_node_->navigator()->GetDelegate()->GetUserAgentOverride();
}
net::HttpRequestHeaders headers;
if (!is_for_commit) {
BrowserContext* browser_context =
frame_tree_node_->navigator()->GetController()->GetBrowserContext();
if (browser_context->GetClientHintsControllerDelegate()) {
net::HttpRequestHeaders client_hints_headers;
browser_context->GetClientHintsControllerDelegate()
->GetAdditionalNavigationRequestClientHintsHeaders(
common_params_.url, &client_hints_headers);
headers.MergeFrom(client_hints_headers);
}
headers.AddHeadersFromString(begin_params_->headers);
AddAdditionalRequestHeaders(
&headers, common_params_.url, common_params_.navigation_type,
frame_tree_node_->navigator()->GetController()->GetBrowserContext(),
common_params.method, user_agent_override,
common_params_.has_user_gesture, common_params.initiator_origin,
frame_tree_node);
if (begin_params_->is_form_submission) {
if (browser_initiated && !commit_params.post_content_type.empty()) {
headers.SetHeaderIfMissing(net::HttpRequestHeaders::kContentType,
commit_params.post_content_type);
} else if (!browser_initiated) {
headers.GetHeader(net::HttpRequestHeaders::kContentType,
&commit_params_.post_content_type);
}
}
blink::mojom::RendererPreferences render_prefs =
frame_tree_node_->render_manager()
->current_host()
->GetDelegate()
->GetRendererPrefs(browser_context);
if (render_prefs.enable_do_not_track)
headers.SetHeader(kDoNotTrackHeader, "1");
}
begin_params_->headers = headers.ToString();
initiator_csp_context_.reset(new InitiatorCSPContext(
common_params_.initiator_csp_info.initiator_csp,
common_params_.initiator_csp_info.initiator_self_source,
std::move(navigation_initiator)));
}
Commit Message: Show an error page if a URL redirects to a javascript: URL.
BUG=935175
Change-Id: Id4a9198d5dff823bc3d324b9de9bff2ee86dc499
Reviewed-on: https://chromium-review.googlesource.com/c/1488152
Commit-Queue: Charlie Reis <[email protected]>
Reviewed-by: Arthur Sonzogni <[email protected]>
Cr-Commit-Position: refs/heads/master@{#635848}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string TestFlashMessageLoop::TestRunWithoutQuit() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::DestroyMessageLoopResourceTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
ASSERT_TRUE(false);
}
ASSERT_EQ(PP_ERROR_ABORTED, result);
PASS();
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
Target: 1
Example 2:
Code: GF_Err dmed_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DMEDBox *ptr = (GF_DMEDBox *)s;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct crypto_alg *crypto_alg_match(struct crypto_user_alg *p, int exact)
{
struct crypto_alg *q, *alg = NULL;
down_read(&crypto_alg_sem);
list_for_each_entry(q, &crypto_alg_list, cra_list) {
int match = 0;
if ((q->cra_flags ^ p->cru_type) & p->cru_mask)
continue;
if (strlen(p->cru_driver_name))
match = !strcmp(q->cra_driver_name,
p->cru_driver_name);
else if (!exact)
match = !strcmp(q->cra_name, p->cru_name);
if (!match)
continue;
if (unlikely(!crypto_mod_get(q)))
continue;
alg = q;
break;
}
up_read(&crypto_alg_sem);
return alg;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Utterance::~Utterance() {
DCHECK_EQ(completion_task_, static_cast<Task *>(NULL));
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool AXListBoxOption::computeAccessibilityIsIgnored(
IgnoredReasons* ignoredReasons) const {
if (!getNode())
return true;
if (accessibilityIsIgnoredByDefault(ignoredReasons))
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PDFiumEngine::MoveRangeSelectionExtent(const pp::Point& extent) {
int page_index = -1;
int char_index = -1;
int form_type = FPDF_FORMFIELD_UNKNOWN;
PDFiumPage::LinkTarget target;
GetCharIndex(extent, &page_index, &char_index, &form_type, &target);
if (page_index < 0 || char_index < 0)
return;
SelectionChangeInvalidator selection_invalidator(this);
if (range_selection_direction_ == RangeSelectionDirection::Right) {
ExtendSelection(page_index, char_index);
return;
}
selection_.clear();
selection_.push_back(PDFiumRange(pages_[page_index].get(), char_index, 0));
GetCharIndex(range_selection_base_, &page_index, &char_index, &form_type,
&target);
ExtendSelection(page_index, char_index);
}
Commit Message: [pdf] Use a temporary list when unloading pages
When traversing the |deferred_page_unloads_| list and handling the
unloads it's possible for new pages to get added to the list which will
invalidate the iterator.
This CL swaps the list with an empty list and does the iteration on the
list copy. New items that are unloaded while handling the defers will be
unloaded at a later point.
Bug: 780450
Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac
Reviewed-on: https://chromium-review.googlesource.com/758916
Commit-Queue: dsinclair <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#515056}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: v8::Handle<v8::Value> V8TestSerializedScriptValueInterface::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestSerializedScriptValueInterface.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, hello, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
MessagePortArray messagePortArrayTransferList;
ArrayBufferArray arrayBufferArrayTransferList;
if (args.Length() > 2) {
if (!extractTransferables(args[2], messagePortArrayTransferList, arrayBufferArrayTransferList))
return V8Proxy::throwTypeError("Could not extract transferables");
}
bool dataDidThrow = false;
RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[1], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate());
if (dataDidThrow)
return v8::Undefined();
RefPtr<TestSerializedScriptValueInterface> impl = TestSerializedScriptValueInterface::create(hello, data, messagePortArrayTransferList);
v8::Handle<v8::Object> wrapper = args.Holder();
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate());
return args.Holder();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: const gfx::ImageSkia PageInfoUI::GetVrSettingsIcon(SkColor related_text_color) {
return gfx::CreateVectorIcon(
kVrHeadsetIcon, kVectorIconSize,
color_utils::DeriveDefaultIconColor(related_text_color));
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static vpx_codec_err_t ctrl_set_skip_loop_filter(vpx_codec_alg_priv_t *ctx,
va_list args) {
ctx->skip_loop_filter = va_arg(args, int);
if (ctx->frame_workers) {
VPxWorker *const worker = ctx->frame_workers;
FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
frame_worker_data->pbi->common.skip_loop_filter = ctx->skip_loop_filter;
}
return VPX_CODEC_OK;
}
Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream
Description from upstream:
vp9: Fix potential SEGV in decoder_peek_si_internal
decoder_peek_si_internal could potentially read more bytes than
what actually exists in the input buffer. We check for the buffer
size to be at least 8, but we try to read up to 10 bytes in the
worst case. A well crafted file could thus cause a segfault.
Likely change that introduced this bug was:
https://chromium-review.googlesource.com/#/c/70439 (git hash:
7c43fb6)
Bug: 30013856
Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3
(cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33)
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int er_supported(ERContext *s)
{
if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice ||
!s->cur_pic.f ||
s->cur_pic.field_picture ||
s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO
)
return 0;
return 1;
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-617
Target: 1
Example 2:
Code: void CL_UpdateMumble(void)
{
vec3_t pos, forward, up;
float scale = cl_mumbleScale->value;
float tmp;
if(!cl_useMumble->integer)
return;
AngleVectors( cl.snap.ps.viewangles, forward, NULL, up);
pos[0] = cl.snap.ps.origin[0] * scale;
pos[1] = cl.snap.ps.origin[2] * scale;
pos[2] = cl.snap.ps.origin[1] * scale;
tmp = forward[1];
forward[1] = forward[2];
forward[2] = tmp;
tmp = up[1];
up[1] = up[2];
up[2] = tmp;
if(cl_useMumble->integer > 1) {
fprintf(stderr, "%f %f %f, %f %f %f, %f %f %f\n",
pos[0], pos[1], pos[2],
forward[0], forward[1], forward[2],
up[0], up[1], up[2]);
}
mumble_update_coordinates(pos, forward, up);
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert,
int *pathLenConstraint)
{
int ret = X509_OK, i = 0;
bigint *cert_sig;
X509_CTX *next_cert = NULL;
BI_CTX *ctx = NULL;
bigint *mod = NULL, *expn = NULL;
int match_ca_cert = 0;
struct timeval tv;
uint8_t is_self_signed = 0;
if (cert == NULL)
{
ret = X509_VFY_ERROR_NO_TRUSTED_CERT;
goto end_verify;
}
/* a self-signed certificate that is not in the CA store - use this
to check the signature */
if (asn1_compare_dn(cert->ca_cert_dn, cert->cert_dn) == 0)
{
is_self_signed = 1;
ctx = cert->rsa_ctx->bi_ctx;
mod = cert->rsa_ctx->m;
expn = cert->rsa_ctx->e;
}
gettimeofday(&tv, NULL);
/* check the not before date */
if (tv.tv_sec < cert->not_before)
{
ret = X509_VFY_ERROR_NOT_YET_VALID;
goto end_verify;
}
/* check the not after date */
if (tv.tv_sec > cert->not_after)
{
ret = X509_VFY_ERROR_EXPIRED;
goto end_verify;
}
if (cert->basic_constraint_present)
{
/* If the cA boolean is not asserted,
then the keyCertSign bit in the key usage extension MUST NOT be
asserted. */
if (!cert->basic_constraint_cA &&
IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN))
{
ret = X509_VFY_ERROR_BASIC_CONSTRAINT;
goto end_verify;
}
/* The pathLenConstraint field is meaningful only if the cA boolean is
asserted and the key usage extension, if present, asserts the
keyCertSign bit. In this case, it gives the maximum number of
non-self-issued intermediate certificates that may follow this
certificate in a valid certification path. */
if (cert->basic_constraint_cA &&
(!cert->key_usage_present ||
IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN)) &&
(cert->basic_constraint_pathLenConstraint+1) < *pathLenConstraint)
{
ret = X509_VFY_ERROR_BASIC_CONSTRAINT;
goto end_verify;
}
}
next_cert = cert->next;
/* last cert in the chain - look for a trusted cert */
if (next_cert == NULL)
{
if (ca_cert_ctx != NULL)
{
/* go thru the CA store */
while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
{
/* the extension is present but the cA boolean is not
asserted, then the certified public key MUST NOT be used
to verify certificate signatures. */
if (cert->basic_constraint_present &&
!ca_cert_ctx->cert[i]->basic_constraint_cA)
continue;
if (asn1_compare_dn(cert->ca_cert_dn,
ca_cert_ctx->cert[i]->cert_dn) == 0)
{
/* use this CA certificate for signature verification */
match_ca_cert = true;
ctx = ca_cert_ctx->cert[i]->rsa_ctx->bi_ctx;
mod = ca_cert_ctx->cert[i]->rsa_ctx->m;
expn = ca_cert_ctx->cert[i]->rsa_ctx->e;
break;
}
i++;
}
}
/* couldn't find a trusted cert (& let self-signed errors
be returned) */
if (!match_ca_cert && !is_self_signed)
{
ret = X509_VFY_ERROR_NO_TRUSTED_CERT;
goto end_verify;
}
}
else if (asn1_compare_dn(cert->ca_cert_dn, next_cert->cert_dn) != 0)
{
/* check the chain */
ret = X509_VFY_ERROR_INVALID_CHAIN;
goto end_verify;
}
else /* use the next certificate in the chain for signature verify */
{
ctx = next_cert->rsa_ctx->bi_ctx;
mod = next_cert->rsa_ctx->m;
expn = next_cert->rsa_ctx->e;
}
/* cert is self signed */
if (!match_ca_cert && is_self_signed)
{
ret = X509_VFY_ERROR_SELF_SIGNED;
goto end_verify;
}
/* check the signature */
cert_sig = sig_verify(ctx, cert->signature, cert->sig_len,
bi_clone(ctx, mod), bi_clone(ctx, expn));
if (cert_sig && cert->digest)
{
if (bi_compare(cert_sig, cert->digest) != 0)
ret = X509_VFY_ERROR_BAD_SIGNATURE;
bi_free(ctx, cert_sig);
}
else
{
ret = X509_VFY_ERROR_BAD_SIGNATURE;
}
bi_clear_cache(ctx);
if (ret)
goto end_verify;
/* go down the certificate chain using recursion. */
if (next_cert != NULL)
{
(*pathLenConstraint)++; /* don't include last certificate */
ret = x509_verify(ca_cert_ctx, next_cert, pathLenConstraint);
}
end_verify:
return ret;
}
Commit Message: Apply CVE fixes for X509 parsing
Apply patches developed by Sze Yiu which correct a vulnerability in
X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info.
CWE ID: CWE-347
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PageCaptureSaveAsMHTMLFunction::RunAsync() {
params_ = SaveAsMHTML::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
AddRef(); // Balanced in ReturnFailure/ReturnSuccess()
#if defined(OS_CHROMEOS)
if (profiles::ArePublicSessionRestrictionsEnabled()) {
WebContents* web_contents = GetWebContents();
if (!web_contents) {
ReturnFailure(kTabClosedError);
return true;
}
auto callback =
base::Bind(&PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest,
base::Unretained(this));
permission_helper::HandlePermissionRequest(
*extension(), {APIPermission::kPageCapture}, web_contents, callback,
permission_helper::PromptFactory());
return true;
}
#endif
base::PostTaskWithTraits(
FROM_HERE, kCreateTemporaryFileTaskTraits,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile,
this));
return true;
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void DrawHighlight(gfx::Canvas* canvas,
const SkPoint& p,
SkScalar radius,
SkColor color) {
const SkColor colors[2] = {color, SkColorSetA(color, 0)};
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setShader(cc::PaintShader::MakeRadialGradient(
p, radius, colors, nullptr, 2, SkTileMode::kClamp));
canvas->sk_canvas()->drawRect(
SkRect::MakeXYWH(p.x() - radius, p.y() - radius, radius * 2, radius * 2),
flags);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
factory_.reset(new FakeURLFetcherFactory());
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 0;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 0;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct usb_host_endpoint *ep_to_host_endpoint(struct usb_device *dev,
unsigned char ep)
{
if (ep & USB_ENDPOINT_DIR_MASK)
return dev->ep_in[ep & USB_ENDPOINT_NUMBER_MASK];
else
return dev->ep_out[ep & USB_ENDPOINT_NUMBER_MASK];
}
Commit Message: USB: usbfs: fix potential infoleak in devio
The stack object “ci” has a total size of 8 bytes. Its last 3 bytes
are padding bytes which are not initialized and leaked to userland
via “copy_to_user”.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
Commit Message:
CWE ID: CWE-320
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
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 <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: MODRET auth_post_retr(cmd_rec *cmd) {
if (auth_anon_allow_robots == TRUE) {
return PR_DECLINED(cmd);
}
if (auth_anon_allow_robots_enabled == TRUE) {
int res;
res = pr_unregister_fs("/robots.txt");
if (res < 0) {
pr_log_debug(DEBUG9, "error removing 'robots' FS for '/robots.txt': %s",
strerror(errno));
}
auth_anon_allow_robots_enabled = FALSE;
}
return PR_DECLINED(cmd);
}
Commit Message: Walk the entire DefaultRoot path, checking for symlinks of any component,
when AllowChrootSymlinks is disabled.
CWE ID: CWE-59
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool TestBrowserWindow::IsAlwaysOnTop() const {
return false;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int usb_audio_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
struct usb_device *dev = interface_to_usbdev(intf);
const struct snd_usb_audio_quirk *quirk =
(const struct snd_usb_audio_quirk *)usb_id->driver_info;
struct snd_usb_audio *chip;
int i, err;
struct usb_host_interface *alts;
int ifnum;
u32 id;
alts = &intf->altsetting[0];
ifnum = get_iface_desc(alts)->bInterfaceNumber;
id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (get_alias_id(dev, &id))
quirk = get_alias_quirk(dev, id);
if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
return -ENXIO;
err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
if (err < 0)
return err;
/*
* found a config. now register to ALSA
*/
/* check whether it's already registered */
chip = NULL;
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (usb_chip[i] && usb_chip[i]->dev == dev) {
if (atomic_read(&usb_chip[i]->shutdown)) {
dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
err = -EIO;
goto __error;
}
chip = usb_chip[i];
atomic_inc(&chip->active); /* avoid autopm */
break;
}
}
if (! chip) {
/* it's a fresh one.
* now look for an empty slot and create a new card instance
*/
for (i = 0; i < SNDRV_CARDS; i++)
if (!usb_chip[i] &&
(vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
(pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
if (enable[i]) {
err = snd_usb_audio_create(intf, dev, i, quirk,
id, &chip);
if (err < 0)
goto __error;
chip->pm_intf = intf;
break;
} else if (vid[i] != -1 || pid[i] != -1) {
dev_info(&dev->dev,
"device (%04x:%04x) is disabled\n",
USB_ID_VENDOR(id),
USB_ID_PRODUCT(id));
err = -ENOENT;
goto __error;
}
}
if (!chip) {
dev_err(&dev->dev, "no available usb audio device\n");
err = -ENODEV;
goto __error;
}
}
dev_set_drvdata(&dev->dev, chip);
/*
* For devices with more than one control interface, we assume the
* first contains the audio controls. We might need a more specific
* check here in the future.
*/
if (!chip->ctrl_intf)
chip->ctrl_intf = alts;
chip->txfr_quirk = 0;
err = 1; /* continue */
if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
/* need some special handlings */
err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
if (err < 0)
goto __error;
}
if (err > 0) {
/* create normal USB audio interfaces */
err = snd_usb_create_streams(chip, ifnum);
if (err < 0)
goto __error;
err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);
if (err < 0)
goto __error;
}
/* we are allowed to call snd_card_register() many times */
err = snd_card_register(chip->card);
if (err < 0)
goto __error;
usb_chip[chip->index] = chip;
chip->num_interfaces++;
usb_set_intfdata(intf, chip);
atomic_dec(&chip->active);
mutex_unlock(®ister_mutex);
return 0;
__error:
if (chip) {
if (!chip->num_interfaces)
snd_card_free(chip->card);
atomic_dec(&chip->active);
}
mutex_unlock(®ister_mutex);
return err;
}
Commit Message: ALSA: usb-audio: Fix UAF decrement if card has no live interfaces in card.c
If a USB sound card reports 0 interfaces, an error condition is triggered
and the function usb_audio_probe errors out. In the error path, there was a
use-after-free vulnerability where the memory object of the card was first
freed, followed by a decrement of the number of active chips. Moving the
decrement above the atomic_dec fixes the UAF.
[ The original problem was introduced in 3.1 kernel, while it was
developed in a different form. The Fixes tag below indicates the
original commit but it doesn't mean that the patch is applicable
cleanly. -- tiwai ]
Fixes: 362e4e49abe5 ("ALSA: usb-audio - clear chip->probing on error exit")
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::getCSSPropertyValuesForShorthandProperties(const StylePropertyShorthand& shorthand) const
{
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
for (size_t i = 0; i < shorthand.length(); ++i) {
RefPtr<CSSValue> value = getPropertyCSSValue(shorthand.properties()[i], DoNotUpdateLayout);
list->append(value);
}
return list.release();
}
Commit Message: Rename isPositioned to isOutOfFlowPositioned for clarity
https://bugs.webkit.org/show_bug.cgi?id=89836
Reviewed by Antti Koivisto.
RenderObject and RenderStyle had an isPositioned() method that was
confusing, because it excluded relative positioning. Rename to
isOutOfFlowPositioned(), which makes it clearer that it only applies
to absolute and fixed positioning.
Simple rename; no behavior change.
Source/WebCore:
* css/CSSComputedStyleDeclaration.cpp:
(WebCore::getPositionOffsetValue):
* css/StyleResolver.cpp:
(WebCore::StyleResolver::collectMatchingRulesForList):
* dom/Text.cpp:
(WebCore::Text::rendererIsNeeded):
* editing/DeleteButtonController.cpp:
(WebCore::isDeletableElement):
* editing/TextIterator.cpp:
(WebCore::shouldEmitNewlinesBeforeAndAfterNode):
* rendering/AutoTableLayout.cpp:
(WebCore::shouldScaleColumns):
* rendering/InlineFlowBox.cpp:
(WebCore::InlineFlowBox::addToLine):
(WebCore::InlineFlowBox::placeBoxesInInlineDirection):
(WebCore::InlineFlowBox::requiresIdeographicBaseline):
(WebCore::InlineFlowBox::adjustMaxAscentAndDescent):
(WebCore::InlineFlowBox::computeLogicalBoxHeights):
(WebCore::InlineFlowBox::placeBoxesInBlockDirection):
(WebCore::InlineFlowBox::flipLinesInBlockDirection):
(WebCore::InlineFlowBox::computeOverflow):
(WebCore::InlineFlowBox::computeOverAnnotationAdjustment):
(WebCore::InlineFlowBox::computeUnderAnnotationAdjustment):
* rendering/InlineIterator.h:
(WebCore::isIteratorTarget):
* rendering/LayoutState.cpp:
(WebCore::LayoutState::LayoutState):
* rendering/RenderBlock.cpp:
(WebCore::RenderBlock::MarginInfo::MarginInfo):
(WebCore::RenderBlock::styleWillChange):
(WebCore::RenderBlock::styleDidChange):
(WebCore::RenderBlock::addChildToContinuation):
(WebCore::RenderBlock::addChildToAnonymousColumnBlocks):
(WebCore::RenderBlock::containingColumnsBlock):
(WebCore::RenderBlock::columnsBlockForSpanningElement):
(WebCore::RenderBlock::addChildIgnoringAnonymousColumnBlocks):
(WebCore::getInlineRun):
(WebCore::RenderBlock::isSelfCollapsingBlock):
(WebCore::RenderBlock::layoutBlock):
(WebCore::RenderBlock::addOverflowFromBlockChildren):
(WebCore::RenderBlock::expandsToEncloseOverhangingFloats):
(WebCore::RenderBlock::handlePositionedChild):
(WebCore::RenderBlock::moveRunInUnderSiblingBlockIfNeeded):
(WebCore::RenderBlock::collapseMargins):
(WebCore::RenderBlock::clearFloatsIfNeeded):
(WebCore::RenderBlock::simplifiedNormalFlowLayout):
(WebCore::RenderBlock::isSelectionRoot):
(WebCore::RenderBlock::blockSelectionGaps):
(WebCore::RenderBlock::clearFloats):
(WebCore::RenderBlock::markAllDescendantsWithFloatsForLayout):
(WebCore::RenderBlock::markSiblingsWithFloatsForLayout):
(WebCore::isChildHitTestCandidate):
(WebCore::InlineMinMaxIterator::next):
(WebCore::RenderBlock::computeBlockPreferredLogicalWidths):
(WebCore::RenderBlock::firstLineBoxBaseline):
(WebCore::RenderBlock::lastLineBoxBaseline):
(WebCore::RenderBlock::updateFirstLetter):
(WebCore::shouldCheckLines):
(WebCore::getHeightForLineCount):
(WebCore::RenderBlock::adjustForBorderFit):
(WebCore::inNormalFlow):
(WebCore::RenderBlock::adjustLinePositionForPagination):
(WebCore::RenderBlock::adjustBlockChildForPagination):
(WebCore::RenderBlock::renderName):
* rendering/RenderBlock.h:
(WebCore::RenderBlock::shouldSkipCreatingRunsForObject):
* rendering/RenderBlockLineLayout.cpp:
(WebCore::RenderBlock::setMarginsForRubyRun):
(WebCore::RenderBlock::computeInlineDirectionPositionsForLine):
(WebCore::RenderBlock::computeBlockDirectionPositionsForLine):
(WebCore::RenderBlock::layoutInlineChildren):
(WebCore::requiresLineBox):
(WebCore::RenderBlock::LineBreaker::skipTrailingWhitespace):
(WebCore::RenderBlock::LineBreaker::skipLeadingWhitespace):
(WebCore::RenderBlock::LineBreaker::nextLineBreak):
* rendering/RenderBox.cpp:
(WebCore::RenderBox::removeFloatingOrPositionedChildFromBlockLists):
(WebCore::RenderBox::styleWillChange):
(WebCore::RenderBox::styleDidChange):
(WebCore::RenderBox::updateBoxModelInfoFromStyle):
(WebCore::RenderBox::offsetFromContainer):
(WebCore::RenderBox::positionLineBox):
(WebCore::RenderBox::computeRectForRepaint):
(WebCore::RenderBox::computeLogicalWidthInRegion):
(WebCore::RenderBox::renderBoxRegionInfo):
(WebCore::RenderBox::computeLogicalHeight):
(WebCore::RenderBox::computePercentageLogicalHeight):
(WebCore::RenderBox::computeReplacedLogicalWidthUsing):
(WebCore::RenderBox::computeReplacedLogicalHeightUsing):
(WebCore::RenderBox::availableLogicalHeightUsing):
(WebCore::percentageLogicalHeightIsResolvable):
* rendering/RenderBox.h:
(WebCore::RenderBox::stretchesToViewport):
(WebCore::RenderBox::isDeprecatedFlexItem):
* rendering/RenderBoxModelObject.cpp:
(WebCore::RenderBoxModelObject::adjustedPositionRelativeToOffsetParent):
(WebCore::RenderBoxModelObject::mapAbsoluteToLocalPoint):
* rendering/RenderBoxModelObject.h:
(WebCore::RenderBoxModelObject::requiresLayer):
* rendering/RenderDeprecatedFlexibleBox.cpp:
(WebCore::childDoesNotAffectWidthOrFlexing):
(WebCore::RenderDeprecatedFlexibleBox::layoutBlock):
(WebCore::RenderDeprecatedFlexibleBox::layoutHorizontalBox):
(WebCore::RenderDeprecatedFlexibleBox::layoutVerticalBox):
(WebCore::RenderDeprecatedFlexibleBox::renderName):
* rendering/RenderFieldset.cpp:
(WebCore::RenderFieldset::findLegend):
* rendering/RenderFlexibleBox.cpp:
(WebCore::RenderFlexibleBox::computePreferredLogicalWidths):
(WebCore::RenderFlexibleBox::autoMarginOffsetInMainAxis):
(WebCore::RenderFlexibleBox::availableAlignmentSpaceForChild):
(WebCore::RenderFlexibleBox::computeMainAxisPreferredSizes):
(WebCore::RenderFlexibleBox::computeNextFlexLine):
(WebCore::RenderFlexibleBox::resolveFlexibleLengths):
(WebCore::RenderFlexibleBox::prepareChildForPositionedLayout):
(WebCore::RenderFlexibleBox::layoutAndPlaceChildren):
(WebCore::RenderFlexibleBox::layoutColumnReverse):
(WebCore::RenderFlexibleBox::adjustAlignmentForChild):
(WebCore::RenderFlexibleBox::flipForRightToLeftColumn):
* rendering/RenderGrid.cpp:
(WebCore::RenderGrid::renderName):
* rendering/RenderImage.cpp:
(WebCore::RenderImage::computeIntrinsicRatioInformation):
* rendering/RenderInline.cpp:
(WebCore::RenderInline::addChildIgnoringContinuation):
(WebCore::RenderInline::addChildToContinuation):
(WebCore::RenderInline::generateCulledLineBoxRects):
(WebCore):
(WebCore::RenderInline::culledInlineFirstLineBox):
(WebCore::RenderInline::culledInlineLastLineBox):
(WebCore::RenderInline::culledInlineVisualOverflowBoundingBox):
(WebCore::RenderInline::computeRectForRepaint):
(WebCore::RenderInline::dirtyLineBoxes):
* rendering/RenderLayer.cpp:
(WebCore::checkContainingBlockChainForPagination):
(WebCore::RenderLayer::updateLayerPosition):
(WebCore::isPositionedContainer):
(WebCore::RenderLayer::calculateClipRects):
(WebCore::RenderLayer::shouldBeNormalFlowOnly):
* rendering/RenderLayerCompositor.cpp:
(WebCore::RenderLayerCompositor::requiresCompositingForPosition):
* rendering/RenderLineBoxList.cpp:
(WebCore::RenderLineBoxList::dirtyLinesFromChangedChild):
* rendering/RenderListItem.cpp:
(WebCore::getParentOfFirstLineBox):
* rendering/RenderMultiColumnBlock.cpp:
(WebCore::RenderMultiColumnBlock::renderName):
* rendering/RenderObject.cpp:
(WebCore::RenderObject::markContainingBlocksForLayout):
(WebCore::RenderObject::setPreferredLogicalWidthsDirty):
(WebCore::RenderObject::invalidateContainerPreferredLogicalWidths):
(WebCore::RenderObject::styleWillChange):
(WebCore::RenderObject::offsetParent):
* rendering/RenderObject.h:
(WebCore::RenderObject::isOutOfFlowPositioned):
(WebCore::RenderObject::isInFlowPositioned):
(WebCore::RenderObject::hasClip):
(WebCore::RenderObject::isFloatingOrOutOfFlowPositioned):
* rendering/RenderObjectChildList.cpp:
(WebCore::RenderObjectChildList::removeChildNode):
* rendering/RenderReplaced.cpp:
(WebCore::hasAutoHeightOrContainingBlockWithAutoHeight):
* rendering/RenderRubyRun.cpp:
(WebCore::RenderRubyRun::rubyText):
* rendering/RenderTable.cpp:
(WebCore::RenderTable::addChild):
(WebCore::RenderTable::computeLogicalWidth):
(WebCore::RenderTable::layout):
* rendering/style/RenderStyle.h:
Source/WebKit/blackberry:
* Api/WebPage.cpp:
(BlackBerry::WebKit::isPositionedContainer):
(BlackBerry::WebKit::isNonRenderViewFixedPositionedContainer):
(BlackBerry::WebKit::isFixedPositionedContainer):
Source/WebKit2:
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::updateOffsetFromViewportForSelf):
git-svn-id: svn://svn.chromium.org/blink/trunk@121123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MhtmlSaveStatus WriteMHTMLToDisk(std::vector<WebThreadSafeData> mhtml_contents,
base::File file) {
TRACE_EVENT0("page-serialization", "WriteMHTMLToDisk (RenderFrameImpl)");
SCOPED_UMA_HISTOGRAM_TIMER(
"PageSerialization.MhtmlGeneration.WriteToDiskTime.SingleFrame");
DCHECK(!RenderThread::Get()) << "Should not run in the main renderer thread";
MhtmlSaveStatus save_status = MhtmlSaveStatus::SUCCESS;
for (const WebThreadSafeData& data : mhtml_contents) {
if (!data.IsEmpty() &&
file.WriteAtCurrentPos(data.Data(), data.size()) < 0) {
save_status = MhtmlSaveStatus::FILE_WRITTING_ERROR;
break;
}
}
file.Close();
return save_status;
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Ins_IUP( INS_ARG )
{
IUP_WorkerRec V;
FT_Byte mask;
FT_UInt first_point; /* first point of contour */
FT_UInt end_point; /* end point (last+1) of contour */
FT_UInt first_touched; /* first touched point in contour */
FT_UInt cur_touched; /* current touched point in contour */
FT_UInt point; /* current point */
FT_Short contour; /* current contour */
FT_UNUSED_ARG;
/* ignore empty outlines */
if ( CUR.pts.n_contours == 0 )
return;
if ( CUR.opcode & 1 )
{
mask = FT_CURVE_TAG_TOUCH_X;
V.orgs = CUR.pts.org;
V.curs = CUR.pts.cur;
V.orus = CUR.pts.orus;
}
else
{
mask = FT_CURVE_TAG_TOUCH_Y;
V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 );
V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 );
V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 );
}
V.max_points = CUR.pts.n_points;
contour = 0;
point = 0;
do
{
end_point = CUR.pts.contours[contour] - CUR.pts.first_point;
first_point = point;
if ( CUR.pts.n_points <= end_point )
end_point = CUR.pts.n_points;
while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 )
point++;
if ( point <= end_point )
{
first_touched = point;
cur_touched = point;
point++;
while ( point <= end_point )
{
if ( ( CUR.pts.tags[point] & mask ) != 0 )
{
if ( point > 0 )
_iup_worker_interpolate( &V,
cur_touched + 1,
point - 1,
cur_touched,
point );
cur_touched = point;
}
point++;
}
if ( cur_touched == first_touched )
_iup_worker_shift( &V, first_point, end_point, cur_touched );
else
{
_iup_worker_interpolate( &V,
(FT_UShort)( cur_touched + 1 ),
end_point,
cur_touched,
first_touched );
if ( first_touched > 0 )
_iup_worker_interpolate( &V,
first_point,
first_touched - 1,
cur_touched,
first_touched );
}
}
contour++;
} while ( contour < CUR.pts.n_contours );
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: getTranslatedShaderSourceANGLE(WebGLId shader) {
GLint logLength = 0;
gl_->GetShaderiv(
shader, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &logLength);
if (!logLength)
return WebKit::WebString();
scoped_array<GLchar> log(new GLchar[logLength]);
if (!log.get())
return WebKit::WebString();
GLsizei returnedLogLength = 0;
gl_->GetTranslatedShaderSourceANGLE(
shader, logLength, &returnedLogLength, log.get());
if (!returnedLogLength)
return WebKit::WebString();
DCHECK_EQ(logLength, returnedLogLength + 1);
WebKit::WebString res =
WebKit::WebString::fromUTF8(log.get(), returnedLogLength);
return res;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dev_get_valid_name(struct net *net,
struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <[email protected]>
Cc: Jason Wang <[email protected]>
Cc: "Michael S. Tsirkin" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
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
Target: 1
Example 2:
Code: bool MediaControlCastButtonElement::keepEventInNode(Event* event) {
return isUserInteractionEvent(event);
}
Commit Message: Fixed volume slider element event handling
MediaControlVolumeSliderElement::defaultEventHandler has making
redundant calls to setVolume() & setMuted() on mouse activity. E.g. if
a mouse click changed the slider position, the above calls were made 4
times, once for each of these events: mousedown, input, mouseup,
DOMActive, click. This crack got exposed when PointerEvents are enabled
by default on M55, adding pointermove, pointerdown & pointerup to the
list.
This CL fixes the code to trigger the calls to setVolume() & setMuted()
only when the slider position is changed. Also added pointer events to
certain lists of mouse events in the code.
BUG=677900
Review-Url: https://codereview.chromium.org/2622273003
Cr-Commit-Position: refs/heads/master@{#446032}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LayoutUnit LayoutBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTop, LayoutBox& child, bool atBeforeSideOfBlock)
{
LayoutBlockFlow* childBlockFlow = child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child) : 0;
LayoutUnit newLogicalTop = applyBeforeBreak(child, logicalTop);
LayoutUnit logicalTopBeforeUnsplittableAdjustment = newLogicalTop;
LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, newLogicalTop);
LayoutUnit paginationStrut = 0;
LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
LayoutUnit childLogicalHeight = child.logicalHeight();
if (unsplittableAdjustmentDelta) {
setPageBreak(newLogicalTop, childLogicalHeight - unsplittableAdjustmentDelta);
paginationStrut = unsplittableAdjustmentDelta;
} else if (childBlockFlow && childBlockFlow->paginationStrut()) {
paginationStrut = childBlockFlow->paginationStrut();
}
if (paginationStrut) {
if (atBeforeSideOfBlock && logicalTop == newLogicalTop && !isOutOfFlowPositioned() && !isTableCell()) {
paginationStrut += logicalTop;
if (isFloating())
paginationStrut += marginBefore(); // Floats' margins do not collapse with page or column boundaries.
setPaginationStrut(paginationStrut);
if (childBlockFlow)
childBlockFlow->setPaginationStrut(0);
} else {
newLogicalTop += paginationStrut;
}
}
if (!unsplittableAdjustmentDelta) {
if (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(newLogicalTop)) {
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(newLogicalTop, AssociateWithLatterPage);
LayoutUnit spaceShortage = childLogicalHeight - remainingLogicalHeight;
if (spaceShortage > 0) {
LayoutUnit spaceShortageInLastColumn = intMod(spaceShortage, pageLogicalHeight);
setPageBreak(newLogicalTop, spaceShortageInLastColumn ? spaceShortageInLastColumn : spaceShortage);
} else if (remainingLogicalHeight == pageLogicalHeight && offsetFromLogicalTopOfFirstPage() + child.logicalTop()) {
setPageBreak(newLogicalTop, childLogicalHeight);
}
}
}
setLogicalHeight(logicalHeight() + (newLogicalTop - logicalTop));
return newLogicalTop;
}
Commit Message: Consistently check if a block can handle pagination strut propagation.
https://codereview.chromium.org/1360753002 got it right for inline child
layout, but did nothing for block child layout.
BUG=329421
[email protected],[email protected]
Review URL: https://codereview.chromium.org/1387553002
Cr-Commit-Position: refs/heads/master@{#352429}
CWE ID: CWE-22
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void free_pipe_info(struct pipe_inode_info *pipe)
{
int i;
for (i = 0; i < pipe->buffers; i++) {
struct pipe_buffer *buf = pipe->bufs + i;
if (buf->ops)
buf->ops->release(pipe, buf);
}
if (pipe->tmp_page)
__free_page(pipe->tmp_page);
kfree(pipe->bufs);
kfree(pipe);
}
Commit Message: pipe: limit the per-user amount of pages allocated in pipes
On no-so-small systems, it is possible for a single process to cause an
OOM condition by filling large pipes with data that are never read. A
typical process filling 4000 pipes with 1 MB of data will use 4 GB of
memory. On small systems it may be tricky to set the pipe max size to
prevent this from happening.
This patch makes it possible to enforce a per-user soft limit above
which new pipes will be limited to a single page, effectively limiting
them to 4 kB each, as well as a hard limit above which no new pipes may
be created for this user. This has the effect of protecting the system
against memory abuse without hurting other users, and still allowing
pipes to work correctly though with less data at once.
The limit are controlled by two new sysctls : pipe-user-pages-soft, and
pipe-user-pages-hard. Both may be disabled by setting them to zero. The
default soft limit allows the default number of FDs per process (1024)
to create pipes of the default size (64kB), thus reaching a limit of 64MB
before starting to create only smaller pipes. With 256 processes limited
to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB =
1084 MB of memory allocated for a user. The hard limit is disabled by
default to avoid breaking existing applications that make intensive use
of pipes (eg: for splicing).
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: ModuleExport void UnregisterMATImage(void)
{
(void) UnregisterMagickInfo("MAT");
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/598
CWE ID: CWE-617
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8Debugger::breakProgram()
{
if (isPaused()) {
DCHECK(!m_runningNestedMessageLoop);
v8::Local<v8::Value> exception;
v8::Local<v8::Array> hitBreakpoints;
handleProgramBreak(m_pausedContext, m_executionState, exception, hitBreakpoints);
return;
}
if (!canBreakProgram())
return;
v8::HandleScope scope(m_isolate);
v8::Local<v8::Function> breakFunction;
if (!V8_FUNCTION_NEW_REMOVE_PROTOTYPE(m_isolate->GetCurrentContext(), &V8Debugger::breakProgramCallback, v8::External::New(m_isolate, this), 0).ToLocal(&breakFunction))
return;
v8::Debug::Call(debuggerContext(), breakFunction).ToLocalChecked();
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WORD32 ih264d_parse_islice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ih264d_init_cabac_contexts(I_SLICE, ps_dec);
ps_dec->i1_prev_mb_qp_delta = 0;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD16 u2_mbx;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
{
UWORD8 u1_mb_type;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
u2_mbx = ps_dec->u2_mbx;
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(
ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type
| D_INTRA_MB;
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_intra_cabac(0, ps_dec);
if(u1_mb_type > 25)
return ERROR_MB_TYPE;
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/* Parse Macroblock Data */
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cabac(ps_dec, ps_cur_mb_info, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(
ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1),
4, 4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
}
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Decoder Update mb count after mb map is set.
Bug: 25928803
Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37
CWE ID: CWE-119
Target: 1
Example 2:
Code: void PaintLayerScrollableArea::ScrollbarManager::DestroyScrollbar(
ScrollbarOrientation orientation) {
Member<Scrollbar>& scrollbar =
orientation == kHorizontalScrollbar ? h_bar_ : v_bar_;
DCHECK(orientation == kHorizontalScrollbar ? !h_bar_is_attached_
: !v_bar_is_attached_);
if (!scrollbar)
return;
ScrollableArea()->SetScrollbarNeedsPaintInvalidation(orientation);
if (orientation == kHorizontalScrollbar)
ScrollableArea()->rebuild_horizontal_scrollbar_layer_ = true;
else
ScrollableArea()->rebuild_vertical_scrollbar_layer_ = true;
if (!scrollbar->IsCustomScrollbar())
ScrollableArea()->WillRemoveScrollbar(*scrollbar, orientation);
ScrollableArea()->GetLayoutBox()->GetDocument().View()->RemoveScrollbar(
scrollbar);
scrollbar->DisconnectFromScrollableArea();
scrollbar = nullptr;
}
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 <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) {
DCHECK(GetFrame());
Document* owner_document = GetFrame()->GetDocument();
if (!owner_document || !GetFrame()->GetPage())
return;
if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs(
owner_document->Url().Protocol()))
return;
String script = DecodeURLEscapeSequences(
url.GetString().Substring(strlen("javascript:")));
UserGestureIndicator gesture_indicator(
UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture));
v8::HandleScope handle_scope(ToIsolate(GetFrame()));
v8::Local<v8::Value> result =
GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script));
if (result.IsEmpty() || !result->IsString())
return;
String script_result = ToCoreString(v8::Local<v8::String>::Cast(result));
if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) {
GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL(
script_result, owner_document);
}
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
PNG_CONST image_transform *transform_list)
{
memset(dp, 0, sizeof *dp);
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->transform_list = transform_list;
/* Local variable fields */
dp->output_colour_type = 255; /* invalid */
dp->output_bit_depth = 255; /* invalid */
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: CustomScrollableView() {}
Commit Message: Make the webstore inline install dialog be tab-modal
Also clean up a few minor lint errors while I'm in here.
BUG=550047
Review URL: https://codereview.chromium.org/1496033003
Cr-Commit-Position: refs/heads/master@{#363925}
CWE ID: CWE-17
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RunLoop::RunLoop()
: delegate_(tls_delegate.Get().Get()),
origin_task_runner_(ThreadTaskRunnerHandle::Get()),
weak_factory_(this) {
DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
"to using RunLoop.";
DCHECK(origin_task_runner_);
}
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).
[email protected]
Bug: 750779
Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448
Reviewed-on: https://chromium-review.googlesource.com/594713
Commit-Queue: Gabriel Charette <[email protected]>
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: danakj <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492263}
CWE ID:
Target: 1
Example 2:
Code: ui::AXMode ChromeContentBrowserClient::GetAXModeForBrowserContext(
content::BrowserContext* browser_context) {
Profile* profile = Profile::FromBrowserContext(browser_context);
return AccessibilityLabelsServiceFactory::GetForProfile(profile)->GetAXMode();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(info ? info->InitialURL().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <[email protected]>
Commit-Queue: Nicolás Peña Moreno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/553
CWE ID: CWE-772
Target: 1
Example 2:
Code: static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
s->dpcm_direction = 0;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
s->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
for (i = 0; i < 3; i++) {
if (mpeg4_decode_dpcm_macroblock(s, (*s->dpcm_macroblock)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
if (get_bits_left(&s->gb) == 0)
return SLICE_END;
if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
return SLICE_END;
return SLICE_OK;
}
Commit Message: avcodec/mpeg4videodec: Check idx in mpeg4_decode_studio_block()
Fixes: Out of array access
Fixes: 13500/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5769760178962432
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: Kieran Kunhya <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tcm_loop_port_unlink(
struct se_portal_group *se_tpg,
struct se_lun *se_lun)
{
struct scsi_device *sd;
struct tcm_loop_hba *tl_hba;
struct tcm_loop_tpg *tl_tpg;
tl_tpg = container_of(se_tpg, struct tcm_loop_tpg, tl_se_tpg);
tl_hba = tl_tpg->tl_hba;
sd = scsi_device_lookup(tl_hba->sh, 0, tl_tpg->tl_tpgt,
se_lun->unpacked_lun);
if (!sd) {
printk(KERN_ERR "Unable to locate struct scsi_device for %d:%d:"
"%d\n", 0, tl_tpg->tl_tpgt, se_lun->unpacked_lun);
return;
}
/*
* Remove Linux/SCSI struct scsi_device by HCTL
*/
scsi_remove_device(sd);
scsi_device_put(sd);
atomic_dec(&tl_tpg->tl_tpg_port_count);
smp_mb__after_atomic_dec();
printk(KERN_INFO "TCM_Loop_ConfigFS: Port Unlink Successful\n");
}
Commit Message: loopback: off by one in tcm_loop_make_naa_tpg()
This is an off by one 'tgpt' check in tcm_loop_make_naa_tpg() that could result
in memory corruption.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas A. Bellinger <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int udp_v6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
struct udphdr *uh;
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi6 *fl6 = &inet->cork.fl.u.ip6;
int err = 0;
int is_udplite = IS_UDPLITE(sk);
__wsum csum = 0;
/* Grab the skbuff where UDP header space exists. */
if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
goto out;
/*
* Create a UDP header
*/
uh = udp_hdr(skb);
uh->source = fl6->fl6_sport;
uh->dest = fl6->fl6_dport;
uh->len = htons(up->len);
uh->check = 0;
if (is_udplite)
csum = udplite_csum_outgoing(sk, skb);
else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr,
up->len);
goto send;
} else
csum = udp_csum_outgoing(sk, skb);
/* add protocol-dependent pseudo-header */
uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
up->len, fl6->flowi6_proto, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
send:
err = ip6_push_pending_frames(sk);
if (err) {
if (err == -ENOBUFS && !inet6_sk(sk)->recverr) {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
err = 0;
}
} else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_OUTDATAGRAMS, is_udplite);
out:
up->len = 0;
up->pending = 0;
return err;
}
Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data
We accidentally call down to ip6_push_pending_frames when uncorking
pending AF_INET data on a ipv6 socket. This results in the following
splat (from Dave Jones):
skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:126!
invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC
Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth
+netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c
CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37
task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000
RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282
RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006
RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520
RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800
R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800
FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600
Stack:
ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4
ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6
ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0
Call Trace:
[<ffffffff8159a9aa>] skb_push+0x3a/0x40
[<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0
[<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140
[<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0
[<ffffffff81694660>] ? udplite_getfrag+0x20/0x20
[<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0
[<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0
[<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40
[<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20
[<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0
[<ffffffff816f5d54>] tracesys+0xdd/0xe2
Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55
RIP [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP <ffff8801e6431de8>
This patch adds a check if the pending data is of address family AF_INET
and directly calls udp_push_ending_frames from udp_v6_push_pending_frames
if that is the case.
This bug was found by Dave Jones with trinity.
(Also move the initialization of fl6 below the AF_INET check, even if
not strictly necessary.)
Cc: Dave Jones <[email protected]>
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: void IRCView::dropEvent(QDropEvent* e)
{
if (e->mimeData() && e->mimeData()->hasUrls())
emit urlsDropped(KUrl::List::fromMimeData(e->mimeData(), KUrl::List::PreferLocalUrls));
}
Commit Message:
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void nbd_recv_coroutines_enter_all(NBDClientSession *s)
{
int i;
for (i = 0; i < MAX_NBD_REQUESTS; i++) {
qemu_coroutine_enter(s->recv_coroutine[i]);
qemu_coroutine_enter(s->recv_coroutine[i]);
}
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ProfileSyncService::OnExperimentsChanged(
const browser_sync::Experiments& experiments) {
if (current_experiments.Matches(experiments))
return;
if (migrator_.get() &&
migrator_->state() != browser_sync::BackendMigrator::IDLE) {
DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
return;
}
const syncable::ModelTypeSet registered_types = GetRegisteredDataTypes();
syncable::ModelTypeSet to_add;
if (experiments.sync_tabs)
to_add.Put(syncable::SESSIONS);
const syncable::ModelTypeSet to_register =
Difference(to_add, registered_types);
DVLOG(2) << "OnExperimentsChanged called with types: "
<< syncable::ModelTypeSetToString(to_add);
DVLOG(2) << "Enabling types: " << syncable::ModelTypeSetToString(to_register);
for (syncable::ModelTypeSet::Iterator it = to_register.First();
it.Good(); it.Inc()) {
RegisterNewDataType(it.Get());
#if !defined(OS_ANDROID)
std::string experiment_name = GetExperimentNameForDataType(it.Get());
if (experiment_name.empty())
continue;
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
experiment_name,
true);
#endif // !defined(OS_ANDROID)
}
if (sync_prefs_.HasKeepEverythingSynced()) {
sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_.get()) {
DVLOG(1) << "Dynamically enabling new datatypes: "
<< syncable::ModelTypeSetToString(to_register);
OnMigrationNeededForTypes(to_register);
}
}
if (experiments.sync_tab_favicons) {
DVLOG(1) << "Enabling syncing of tab favicons.";
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
"sync-tab-favicons",
true);
}
current_experiments = experiments;
}
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
Target: 1
Example 2:
Code: static int ssd_int8_vs_int16_c(const int8_t *pix1, const int16_t *pix2,
int size){
int score=0;
int i;
for(i=0; i<size; i++)
score += (pix1[i]-pix2[i])*(pix1[i]-pix2[i]);
return score;
}
Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-189
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */
{
#ifdef HAVE_SYSLOG_H
if (fpm_globals.error_log_fd == ZLOG_SYSLOG) {
closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */
} else
#endif
/* Notice: child cannot use master error_log
* because not aware when being reopen
* else, should use if (!fpm_use_error_log())
*/
if (fpm_globals.error_log_fd > 0) {
close(fpm_globals.error_log_fd);
}
fpm_globals.error_log_fd = -1;
zlog_set_fd(-1);
if (wp->listening_socket != STDIN_FILENO) {
if (0 > dup2(wp->listening_socket, STDIN_FILENO)) {
zlog(ZLOG_SYSERROR, "failed to init child stdio: dup2()");
return -1;
}
}
return 0;
}
/* }}} */
Commit Message: Fixed bug #73342
Directly listen on socket, instead of duping it to STDIN and
listening on that.
CWE ID: CWE-400
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: atol10(const char *p, size_t char_cnt)
{
uint64_t l;
int digit;
l = 0;
digit = *p - '0';
while (digit >= 0 && digit < 10 && char_cnt-- > 0) {
l = (l * 10) + digit;
digit = *++p - '0';
}
return (l);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
CWE ID: CWE-125
Target: 1
Example 2:
Code: int imap_account_match(const struct Account *a1, const struct Account *a2)
{
struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW);
struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW);
const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account;
const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account;
return mutt_account_match(a1_canon, a2_canon);
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-77
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void cryptd_free_ablkcipher(struct cryptd_ablkcipher *tfm)
{
crypto_free_ablkcipher(&tfm->base);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, RE_LEX_ENVIRONMENT *lex_env)
{
YYUSE (yyvaluep);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
switch (yytype)
{
case 6: /* _CLASS_ */
#line 96 "re_grammar.y" /* yacc.c:1257 */
{ yr_free(((*yyvaluep).class_vector)); }
#line 1045 "re_grammar.c" /* yacc.c:1257 */
break;
case 26: /* alternative */
#line 97 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1051 "re_grammar.c" /* yacc.c:1257 */
break;
case 27: /* concatenation */
#line 98 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1057 "re_grammar.c" /* yacc.c:1257 */
break;
case 28: /* repeat */
#line 99 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1063 "re_grammar.c" /* yacc.c:1257 */
break;
case 29: /* single */
#line 100 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1069 "re_grammar.c" /* yacc.c:1257 */
break;
default:
break;
}
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
Commit Message: Fix issue #674. Move regexp limits to limits.h.
CWE ID: CWE-674
Target: 1
Example 2:
Code: void TextTrackCueList::UpdateCueIndex(TextTrackCue* cue) {
if (!Remove(cue))
return;
Add(cue);
}
Commit Message: Support negative timestamps of TextTrackCue
Ensure proper behaviour for negative timestamps of TextTrackCue.
1. Cues with negative startTime should become active from 0s.
2. Cues with negative startTime and endTime should never be active.
Bug: 314032
Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d
Reviewed-on: https://chromium-review.googlesource.com/863270
Commit-Queue: srirama chandra sekhar <[email protected]>
Reviewed-by: Fredrik Söderquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529012}
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: get_min_filtered_sample_size(void)
{
return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
DFLT_MIN_FILTERED_SAMPLE_SIZE,
1, INT32_MAX);
}
Commit Message: Consider the exit family when applying guard restrictions.
When the new path selection logic went into place, I accidentally
dropped the code that considered the _family_ of the exit node when
deciding if the guard was usable, and we didn't catch that during
code review.
This patch makes the guard_restriction_t code consider the exit
family as well, and adds some (hopefully redundant) checks for the
case where we lack a node_t for a guard but we have a bridge_info_t
for it.
Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006
and CVE-2017-0377.
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
return ret;
}
Commit Message:
CWE ID: CWE-190
Target: 1
Example 2:
Code: ft_black_reset( black_PRaster raster,
char* pool_base,
long pool_size )
{
if ( raster )
{
if ( pool_base && pool_size >= (long)sizeof ( black_TWorker ) + 2048 )
{
black_PWorker worker = (black_PWorker)pool_base;
raster->buffer = pool_base + ( ( sizeof ( *worker ) + 7 ) & ~7 );
raster->buffer_size = (long)( pool_base + pool_size -
(char*)raster->buffer );
raster->worker = worker;
}
else
{
raster->buffer = NULL;
raster->buffer_size = 0;
raster->worker = NULL;
}
}
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void cgsleep_us(int64_t us)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_us_r(&ts_start, us);
}
Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime.
Might have introduced a memory leak, don't have time to check. :(
Should the other hex2bin()'s be checked?
Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this.
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BaseRenderingContext2D::drawImage(ScriptState* script_state,
CanvasImageSource* image_source,
double sx,
double sy,
double sw,
double sh,
double dx,
double dy,
double dw,
double dh,
ExceptionState& exception_state) {
if (!DrawingCanvas())
return;
double start_time = 0;
Optional<CustomCountHistogram> timer;
if (!IsPaint2D()) {
start_time = WTF::MonotonicallyIncreasingTime();
if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) {
if (image_source->IsVideoElement()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_video_gpu,
("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_video_gpu);
} else if (image_source->IsCanvasElement()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_canvas_gpu,
("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_canvas_gpu);
} else if (image_source->IsSVGSource()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_svggpu,
("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_svggpu);
} else if (image_source->IsImageBitmap()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_image_bitmap_gpu,
("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_image_bitmap_gpu);
} else if (image_source->IsOffscreenCanvas()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu,
("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_offscreencanvas_gpu);
} else {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_others_gpu,
("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_others_gpu);
}
} else {
if (image_source->IsVideoElement()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_video_cpu,
("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_video_cpu);
} else if (image_source->IsCanvasElement()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_canvas_cpu,
("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_canvas_cpu);
} else if (image_source->IsSVGSource()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_svgcpu,
("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_svgcpu);
} else if (image_source->IsImageBitmap()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_image_bitmap_cpu,
("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_image_bitmap_cpu);
} else if (image_source->IsOffscreenCanvas()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu,
("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_offscreencanvas_cpu);
} else {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scoped_us_counter_others_cpu,
("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50));
timer.emplace(scoped_us_counter_others_cpu);
}
}
}
scoped_refptr<Image> image;
FloatSize default_object_size(Width(), Height());
SourceImageStatus source_image_status = kInvalidSourceImageStatus;
if (!image_source->IsVideoElement()) {
AccelerationHint hint =
(HasImageBuffer() && GetImageBuffer()->IsAccelerated())
? kPreferAcceleration
: kPreferNoAcceleration;
image = image_source->GetSourceImageForCanvas(&source_image_status, hint,
kSnapshotReasonDrawImage,
default_object_size);
if (source_image_status == kUndecodableSourceImageStatus) {
exception_state.ThrowDOMException(
kInvalidStateError,
"The HTMLImageElement provided is in the 'broken' state.");
}
if (!image || !image->width() || !image->height())
return;
} else {
if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame())
return;
}
if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) ||
!std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) ||
!std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh)
return;
FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh));
FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh));
FloatSize image_size = image_source->ElementSize(default_object_size);
ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect,
&dst_rect);
image_source->AdjustDrawRects(&src_rect, &dst_rect);
if (src_rect.IsEmpty())
return;
DisableDeferralReason reason = kDisableDeferralReasonUnknown;
if (ShouldDisableDeferral(image_source, &reason))
DisableDeferral(reason);
else if (image->IsTextureBacked())
DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage);
ValidateStateStack();
WillDrawImage(image_source);
ValidateStateStack();
ImageBuffer* buffer = GetImageBuffer();
if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) {
float src_area = src_rect.Width() * src_rect.Height();
if (src_area >
CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) {
this->DisableAcceleration();
} else if (src_area > CanvasHeuristicParameters::
kDrawImageTextureUploadSoftSizeLimit) {
SkRect bounds = dst_rect;
SkMatrix ctm = DrawingCanvas()->getTotalMatrix();
ctm.mapRect(&bounds);
float dst_area = dst_rect.Width() * dst_rect.Height();
if (src_area >
dst_area * CanvasHeuristicParameters::
kDrawImageTextureUploadSoftSizeLimitScaleThreshold) {
this->DisableAcceleration();
}
}
}
ValidateStateStack();
if (OriginClean() &&
WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) {
SetOriginTainted();
ClearResolvedFilters();
}
Draw(
[this, &image_source, &image, &src_rect, dst_rect](
PaintCanvas* c, const PaintFlags* flags) // draw lambda
{
DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect,
flags);
},
[this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda
{ return RectContainsTransformedRect(dst_rect, clip_bounds); },
dst_rect, CanvasRenderingContext2DState::kImagePaintType,
image_source->IsOpaque()
? CanvasRenderingContext2DState::kOpaqueImage
: CanvasRenderingContext2DState::kNonOpaqueImage);
ValidateStateStack();
if (!IsPaint2D()) {
DCHECK(start_time);
timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) *
WTF::Time::kMicrosecondsPerSecond);
}
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void __wake_up(wait_queue_head_t *q, unsigned int mode,
int nr_exclusive, void *key)
{
unsigned long flags;
spin_lock_irqsave(&q->lock, flags);
__wake_up_common(q, mode, nr_exclusive, 0, key);
spin_unlock_irqrestore(&q->lock, flags);
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: DrawingBufferClientRestorePixelPackParameters() {
if (!ContextGL())
return;
ContextGL()->PixelStorei(GL_PACK_ROW_LENGTH, pack_row_length_);
ContextGL()->PixelStorei(GL_PACK_SKIP_ROWS, pack_skip_rows_);
ContextGL()->PixelStorei(GL_PACK_SKIP_PIXELS, pack_skip_pixels_);
WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackParameters();
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image(filename_path, fdt);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderFrameHostImpl::InsertVisualStateCallback(
VisualStateCallback callback) {
static uint64_t next_id = 1;
uint64_t key = next_id++;
Send(new FrameMsg_VisualStateRequest(routing_id_, key));
visual_state_callbacks_.emplace(key, std::move(callback));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BinaryUploadService::IsAuthorized(AuthorizationCallback callback) {
if (!timer_.IsRunning()) {
timer_.Start(FROM_HERE, base::TimeDelta::FromHours(24), this,
&BinaryUploadService::ResetAuthorizationData);
}
if (!can_upload_data_.has_value()) {
if (!pending_validate_data_upload_request_) {
std::string dm_token = GetDMToken();
if (dm_token.empty()) {
std::move(callback).Run(false);
return;
}
pending_validate_data_upload_request_ = true;
auto request = std::make_unique<ValidateDataUploadRequest>(base::BindOnce(
&BinaryUploadService::ValidateDataUploadRequestCallback,
weakptr_factory_.GetWeakPtr()));
request->set_dm_token(dm_token);
UploadForDeepScanning(std::move(request));
}
authorization_callbacks_.push_back(std::move(callback));
return;
}
std::move(callback).Run(can_upload_data_.value());
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void print_channel_netjoins(char *channel, TEMP_PRINT_REC *rec,
NETJOIN_SERVER_REC *server)
{
if (rec->nicks->len > 0)
g_string_truncate(rec->nicks, rec->nicks->len-2);
printformat(server->server, channel, MSGLEVEL_JOINS,
rec->count > netjoin_max_nicks ?
IRCTXT_NETSPLIT_JOIN_MORE : IRCTXT_NETSPLIT_JOIN,
rec->nicks->str, rec->count-netjoin_max_nicks);
g_string_free(rec->nicks, TRUE);
g_free(rec);
g_free(channel);
}
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool StopInputMethodProcess() {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive";
return false;
}
ibus_bus_exit_async(ibus_,
FALSE /* do not restart */,
-1 /* timeout */,
NULL /* cancellable */,
NULL /* callback */,
NULL /* user_data */);
if (ibus_config_) {
g_object_unref(ibus_config_);
ibus_config_ = NULL;
}
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool CheckDts(const uint8_t* buffer, int buffer_size) {
RCHECK(buffer_size > 11);
int offset = 0;
while (offset + 11 < buffer_size) {
BitReader reader(buffer + offset, 11);
RCHECK(ReadBits(&reader, 32) == 0x7ffe8001);
reader.SkipBits(1 + 5);
RCHECK(ReadBits(&reader, 1) == 0); // CPF must be 0.
RCHECK(ReadBits(&reader, 7) >= 5);
int frame_size = ReadBits(&reader, 14);
RCHECK(frame_size >= 95);
reader.SkipBits(6);
RCHECK(kSamplingFrequencyValid[ReadBits(&reader, 4)]);
RCHECK(ReadBits(&reader, 5) <= 25);
RCHECK(ReadBits(&reader, 1) == 0);
reader.SkipBits(1 + 1 + 1 + 1);
RCHECK(kExtAudioIdValid[ReadBits(&reader, 3)]);
reader.SkipBits(1 + 1);
RCHECK(ReadBits(&reader, 2) != 3);
offset += frame_size + 1;
}
return true;
}
Commit Message: Cleanup media BitReader ReadBits() calls
Initialize temporary values, check return values.
Small tweaks to solution proposed by [email protected].
Bug: 929962
Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735
Reviewed-on: https://chromium-review.googlesource.com/c/1481085
Commit-Queue: Chrome Cunningham <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#634889}
CWE ID: CWE-200
Target: 1
Example 2:
Code: ChildProcessSecurityPolicy* ChildProcessSecurityPolicy::GetInstance() {
return ChildProcessSecurityPolicyImpl::GetInstance();
}
Commit Message: Apply missing kParentDirectory check
BUG=161564
Review URL: https://chromiumcodereview.appspot.com/11414046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168692 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int utf8len(const uint8_t *b)
{
int len = 0;
int val;
while (*b) {
GET_UTF8(val, *b++, return -1;)
len++;
}
return len;
}
Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known
The version 1 needs the channel count and would divide by 0
Fixes: division by 0
Fixes: fpe_movenc.c_1108_1.ogg
Fixes: fpe_movenc.c_1108_2.ogg
Fixes: fpe_movenc.c_1108_3.wav
Found-by: #CHEN HONGXU# <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-369
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static js_Ast *memberexp(js_State *J)
{
js_Ast *a;
INCREC();
a = newexp(J);
loop:
if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; }
if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; }
DECREC();
return a;
}
Commit Message:
CWE ID: CWE-674
Target: 1
Example 2:
Code: line_construct_pts(LINE *line, Point *pt1, Point *pt2)
{
if (FPeq(pt1->x, pt2->x))
{ /* vertical */
/* use "x = C" */
line->A = -1;
line->B = 0;
line->C = pt1->x;
#ifdef GEODEBUG
printf("line_construct_pts- line is vertical\n");
#endif
}
else if (FPeq(pt1->y, pt2->y))
{ /* horizontal */
/* use "y = C" */
line->A = 0;
line->B = -1;
line->C = pt1->y;
#ifdef GEODEBUG
printf("line_construct_pts- line is horizontal\n");
#endif
}
else
{
/* use "mx - y + yinter = 0" */
line->A = (pt2->y - pt1->y) / (pt2->x - pt1->x);
line->B = -1.0;
line->C = pt1->y - line->A * pt1->x;
/* on some platforms, the preceding expression tends to produce -0 */
if (line->C == 0.0)
line->C = 0.0;
#ifdef GEODEBUG
printf("line_construct_pts- line is neither vertical nor horizontal (diffs x=%.*g, y=%.*g\n",
DBL_DIG, (pt2->x - pt1->x), DBL_DIG, (pt2->y - pt1->y));
#endif
}
}
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
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void rds_tcp_exit(void)
{
rds_tcp_set_unloading();
synchronize_rcu();
rds_info_deregister_func(RDS_INFO_TCP_SOCKETS, rds_tcp_tc_info);
#if IS_ENABLED(CONFIG_IPV6)
rds_info_deregister_func(RDS6_INFO_TCP_SOCKETS, rds6_tcp_tc_info);
#endif
unregister_pernet_device(&rds_tcp_net_ops);
rds_tcp_destroy_conns();
rds_trans_unregister(&rds_tcp_transport);
rds_tcp_recv_exit();
kmem_cache_destroy(rds_tcp_conn_slab);
}
Commit Message: net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().
When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.
In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.
Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.
rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <[email protected]>
==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721
CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0x120/0x188 lib/dump_stack.c:113
print_address_description+0x68/0x278 mm/kasan/report.c:253
kasan_report_error mm/kasan/report.c:351 [inline]
kasan_report+0x21c/0x348 mm/kasan/report.c:409
__asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
__sock_create+0x4f8/0x770 net/socket.c:1276
sock_create_kern+0x50/0x68 net/socket.c:1322
rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
Allocated by task 687:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2705 [inline]
slab_alloc mm/slub.c:2713 [inline]
kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
kmem_cache_zalloc include/linux/slab.h:697 [inline]
net_alloc net/core/net_namespace.c:384 [inline]
copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
ksys_unshare+0x340/0x628 kernel/fork.c:2577
__do_sys_unshare kernel/fork.c:2645 [inline]
__se_sys_unshare kernel/fork.c:2643 [inline]
__arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960
Freed by task 264:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
__kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
slab_free_hook mm/slub.c:1370 [inline]
slab_free_freelist_hook mm/slub.c:1397 [inline]
slab_free mm/slub.c:2952 [inline]
kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
net_free net/core/net_namespace.c:400 [inline]
net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
net_drop_ns net/core/net_namespace.c:406 [inline]
cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
The buggy address belongs to the object at ffff8003496a3f80
which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
Element* root = document.documentElement();
m_fontSelector->registerForInvalidationCallbacks(this);
CSSDefaultStyleSheets::initDefaultStyle(root);
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: mem_to_page(
void *addr)
{
if ((!is_vmalloc_addr(addr))) {
return virt_to_page(addr);
} else {
return vmalloc_to_page(addr);
}
}
Commit Message: xfs: fix _xfs_buf_find oops on blocks beyond the filesystem end
When _xfs_buf_find is passed an out of range address, it will fail
to find a relevant struct xfs_perag and oops with a null
dereference. This can happen when trying to walk a filesystem with a
metadata inode that has a partially corrupted extent map (i.e. the
block number returned is corrupt, but is otherwise intact) and we
try to read from the corrupted block address.
In this case, just fail the lookup. If it is readahead being issued,
it will simply not be done, but if it is real read that fails we
will get an error being reported. Ideally this case should result
in an EFSCORRUPTED error being reported, but we cannot return an
error through xfs_buf_read() or xfs_buf_get() so this lookup failure
may result in ENOMEM or EIO errors being reported instead.
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Reviewed-by: Ben Myers <[email protected]>
Signed-off-by: Ben Myers <[email protected]>
CWE ID: CWE-20
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
Commit Message:
CWE ID: CWE-772
Target: 1
Example 2:
Code: nfsd4_decode_free_stateid(struct nfsd4_compoundargs *argp,
struct nfsd4_free_stateid *free_stateid)
{
DECODE_HEAD;
READ_BUF(sizeof(stateid_t));
free_stateid->fr_stateid.si_generation = be32_to_cpup(p++);
COPYMEM(&free_stateid->fr_stateid.si_opaque, sizeof(stateid_opaque_t));
DECODE_TAIL;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLClearFramebufferTest::InitDraw() {
static const char* v_shader_str =
"attribute vec4 a_Position;\n"
"uniform float u_depth;\n"
"void main()\n"
"{\n"
" gl_Position = a_Position;\n"
" gl_Position.z = u_depth;\n"
"}\n";
static const char* f_shader_str =
"precision mediump float;\n"
"uniform vec4 u_draw_color;\n"
"void main()\n"
"{\n"
" gl_FragColor = u_draw_color;\n"
"}\n";
GLuint program = GLTestHelper::LoadProgram(v_shader_str, f_shader_str);
DCHECK(program);
glUseProgram(program);
GLuint position_loc = glGetAttribLocation(program, "a_Position");
GLTestHelper::SetupUnitQuad(position_loc);
color_handle_ = glGetUniformLocation(program, "u_draw_color");
DCHECK(color_handle_ != static_cast<GLuint>(-1));
depth_handle_ = glGetUniformLocation(program, "u_depth");
DCHECK(depth_handle_ != static_cast<GLuint>(-1));
}
Commit Message: Validate glClearBuffer*v function |buffer| param on the client side
Otherwise we could read out-of-bounds even if an invalid |buffer| is passed
in and in theory we should not read the buffer at all.
BUG=908749
TEST=gl_tests in ASAN build
[email protected]
Change-Id: I94b69b56ce3358ff9bfc0e21f0618aec4371d1ec
Reviewed-on: https://chromium-review.googlesource.com/c/1354571
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#612023}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
fsize = st.st_size;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
Commit Message: - limit the number of program and section header number of sections to be
processed to avoid excessive processing time.
- if a bad note is found, return 0 to stop processing immediately.
CWE ID: CWE-399
Target: 1
Example 2:
Code: ModuleExport size_t RegisterPICTImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PICT","PCT","Apple Macintosh QuickDraw/PICT");
entry->decoder=(DecodeImageHandler *) ReadPICTImage;
entry->encoder=(EncodeImageHandler *) WritePICTImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->magick=(IsImageFormatHandler *) IsPICT;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PICT","PICT","Apple Macintosh QuickDraw/PICT");
entry->decoder=(DecodeImageHandler *) ReadPICTImage;
entry->encoder=(EncodeImageHandler *) WritePICTImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->magick=(IsImageFormatHandler *) IsPICT;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message:
CWE ID: CWE-189
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
} else {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ZVAL_FALSE(&ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
Commit Message:
CWE ID: CWE-502
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParseCDSect(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int r, rl;
int s, sl;
int cur, l;
int count = 0;
/* Check 2.6.0 was NXT(0) not RAW */
if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
SKIP(9);
} else
return;
ctxt->instate = XML_PARSER_CDATA_SECTION;
r = CUR_CHAR(rl);
if (!IS_CHAR(r)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(rl);
s = CUR_CHAR(sl);
if (!IS_CHAR(s)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(sl);
cur = CUR_CHAR(l);
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
while (IS_CHAR(cur) &&
((r != ']') || (s != ']') || (cur != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = tmp;
}
COPY_BUF(rl,buf,len,r);
r = s;
rl = sl;
s = cur;
sl = l;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
buf[len] = 0;
ctxt->instate = XML_PARSER_CONTENT;
if (cur != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
"CData section not finished\n%.50s\n", buf);
xmlFree(buf);
return;
}
NEXTL(l);
/*
* OK the buffer is to be consumed as cdata.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData, buf, len);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, len);
}
xmlFree(buf);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: pgp_decipher(sc_card_t *card, const u8 *in, size_t inlen,
u8 *out, size_t outlen)
{
struct pgp_priv_data *priv = DRVDATA(card);
sc_security_env_t *env = &priv->sec_env;
sc_apdu_t apdu;
u8 apdu_case = SC_APDU_CASE_4;
u8 *temp = NULL;
int r;
LOG_FUNC_CALLED(card->ctx);
/* padding according to OpenPGP card spec 1.1 & 2.x section 7.2.9 / 3.x section 7.2.11 */
if (!(temp = malloc(inlen + 1)))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
/* padding byte: 0x00 = RSA; 0x02 = AES [v2.1+ only] */
temp[0] = 0x00;
memcpy(temp + 1, in, inlen);
in = temp;
inlen += 1;
if (env->operation != SC_SEC_OPERATION_DECIPHER) {
free(temp);
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
"invalid operation");
}
switch (env->key_ref[0]) {
case 0x01: /* Decryption key */
case 0x02: /* authentication key */
/* PSO DECIPHER */
sc_format_apdu(card, &apdu, apdu_case, 0x2A, 0x80, 0x86);
break;
case 0x00: /* signature key */
default:
free(temp);
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
"invalid key reference");
}
/* Gnuk only supports short APDU, so we need to use command chaining */
if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
apdu.flags |= SC_APDU_FLAGS_CHAINING;
}
/* if card/reader does not support extended APDUs, but chaining, then set it */
if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
apdu.flags |= SC_APDU_FLAGS_CHAINING;
apdu.lc = inlen;
apdu.data = (u8 *)in;
apdu.datalen = inlen;
apdu.le = ((outlen >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : outlen;
apdu.resp = out;
apdu.resplen = outlen;
r = sc_transmit_apdu(card, &apdu);
free(temp);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: exsltFuncFunctionComp (xsltStylesheetPtr style, xmlNodePtr inst) {
xmlChar *name, *prefix;
xmlNsPtr ns;
xmlHashTablePtr data;
exsltFuncFunctionData *func;
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
{
xmlChar *qname;
qname = xmlGetProp(inst, (const xmlChar *) "name");
name = xmlSplitQName2 (qname, &prefix);
xmlFree(qname);
}
if ((name == NULL) || (prefix == NULL)) {
xsltGenericError(xsltGenericErrorContext,
"func:function: not a QName\n");
if (name != NULL)
xmlFree(name);
return;
}
/* namespace lookup */
ns = xmlSearchNs (inst->doc, inst, prefix);
if (ns == NULL) {
xsltGenericError(xsltGenericErrorContext,
"func:function: undeclared prefix %s\n",
prefix);
xmlFree(name);
xmlFree(prefix);
return;
}
xmlFree(prefix);
xsltParseTemplateContent(style, inst);
/*
* Create function data
*/
func = exsltFuncNewFunctionData();
func->content = inst->children;
while (IS_XSLT_ELEM(func->content) &&
IS_XSLT_NAME(func->content, "param")) {
func->content = func->content->next;
func->nargs++;
}
/*
* Register the function data such that it can be retrieved
* by exslFuncFunctionFunction
*/
#ifdef XSLT_REFACTORED
/*
* Ensure that the hash table will be stored in the *current*
* stylesheet level in order to correctly evaluate the
* import precedence.
*/
data = (xmlHashTablePtr)
xsltStyleStylesheetLevelGetExtData(style,
EXSLT_FUNCTIONS_NAMESPACE);
#else
data = (xmlHashTablePtr)
xsltStyleGetExtData (style, EXSLT_FUNCTIONS_NAMESPACE);
#endif
if (data == NULL) {
xsltGenericError(xsltGenericErrorContext,
"exsltFuncFunctionComp: no stylesheet data\n");
xmlFree(name);
return;
}
if (xmlHashAddEntry2 (data, ns->href, name, func) < 0) {
xsltTransformError(NULL, style, inst,
"Failed to register function {%s}%s\n",
ns->href, name);
style->errors++;
} else {
xsltGenericDebug(xsltGenericDebugContext,
"exsltFuncFunctionComp: register {%s}%s\n",
ns->href, name);
}
xmlFree(name);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void schedule_debug(struct task_struct *prev)
{
#ifdef CONFIG_SCHED_STACK_END_CHECK
BUG_ON(task_stack_end_corrupted(prev));
#endif
if (unlikely(in_atomic_preempt_off())) {
__schedule_bug(prev);
preempt_count_set(PREEMPT_DISABLED);
}
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void update_free_window_state(WINDOW_STATE_ORDER* window_state)
{
if (!window_state)
return;
free(window_state->titleInfo.string);
window_state->titleInfo.string = NULL;
free(window_state->windowRects);
window_state->windowRects = NULL;
free(window_state->visibilityRects);
window_state->visibilityRects = NULL;
}
Commit Message: Fixed CVE-2018-8786
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SendKeyPress(ui::KeyboardCode key_code, int flags) {
event_generator_->PressKey(key_code, flags);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sec_recv(RD_BOOL * is_fastpath)
{
uint8 fastpath_hdr, fastpath_flags;
uint16 sec_flags;
uint16 channel;
STREAM s;
while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)
{
if (*is_fastpath == True)
{
/* If fastpath packet is encrypted, read data
signature and decrypt */
/* FIXME: extracting flags from hdr could be made less obscure */
fastpath_flags = (fastpath_hdr & 0xC0) >> 6;
if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
return s;
}
if (g_encryption || (!g_licence_issued && !g_licence_error_result))
{
/* TS_SECURITY_HEADER */
in_uint16_le(s, sec_flags);
in_uint8s(s, 2); /* skip sec_flags_hi */
if (g_encryption)
{
if (sec_flags & SEC_ENCRYPT)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
if (sec_flags & SEC_REDIRECTION_PKT)
{
uint8 swapbyte;
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
/* Check for a redirect packet, starts with 00 04 */
if (s->p[0] == 0 && s->p[1] == 4)
{
/* for some reason the PDU and the length seem to be swapped.
This isn't good, but we're going to do a byte for byte
swap. So the first four value appear as: 00 04 XX YY,
where XX YY is the little endian length. We're going to
use 04 00 as the PDU type, so after our swap this will look
like: XX YY 04 00 */
swapbyte = s->p[0];
s->p[0] = s->p[2];
s->p[2] = swapbyte;
swapbyte = s->p[1];
s->p[1] = s->p[3];
s->p[3] = swapbyte;
swapbyte = s->p[2];
s->p[2] = s->p[3];
s->p[3] = swapbyte;
}
}
}
else
{
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
s->p -= 4;
}
}
if (channel != MCS_GLOBAL_CHANNEL)
{
channel_process(s, channel);
continue;
}
return s;
}
return NULL;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
Target: 1
Example 2:
Code: void vb2_ops_wait_prepare(struct vb2_queue *vq)
{
mutex_unlock(vq->lock);
}
Commit Message: [media] videobuf2-v4l2: Verify planes array in buffer dequeueing
When a buffer is being dequeued using VIDIOC_DQBUF IOCTL, the exact buffer
which will be dequeued is not known until the buffer has been removed from
the queue. The number of planes is specific to a buffer, not to the queue.
This does lead to the situation where multi-plane buffers may be requested
and queued with n planes, but VIDIOC_DQBUF IOCTL may be passed an argument
struct with fewer planes.
__fill_v4l2_buffer() however uses the number of planes from the dequeued
videobuf2 buffer, overwriting kernel memory (the m.planes array allocated
in video_usercopy() in v4l2-ioctl.c) if the user provided fewer
planes than the dequeued buffer had. Oops!
Fixes: b0e0e1f83de3 ("[media] media: videobuf2: Prepare to divide videobuf2")
Signed-off-by: Sakari Ailus <[email protected]>
Acked-by: Hans Verkuil <[email protected]>
Cc: [email protected] # for v4.4 and later
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id,
const QString &app_icon, const QString &summary, const QString &body,
const QStringList &actions, const QVariantMap &hints, int timeout)
{
uint partOf = 0;
const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString();
const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString();
const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool();
if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) {
partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt();
}
qDebug() << "Currrent active notifications:" << m_activeNotifications;
qDebug() << "Guessing partOf as:" << partOf;
qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf;
QString _body;
if (partOf > 0) {
const QString source = QStringLiteral("notification %1").arg(partOf);
Plasma::DataContainer *container = containerForSource(source);
if (container) {
_body = container->data()[QStringLiteral("body")].toString();
if (_body != body) {
_body.append("\n").append(body);
} else {
_body = body;
}
replaces_id = partOf;
CloseNotification(partOf);
}
}
uint id = replaces_id ? replaces_id : m_nextId++;
if (m_alwaysReplaceAppsList.contains(app_name)) {
if (m_notificationsFromReplaceableApp.contains(app_name)) {
id = m_notificationsFromReplaceableApp.value(app_name);
} else {
m_notificationsFromReplaceableApp.insert(app_name, id);
}
}
QString appname_str = app_name;
if (appname_str.isEmpty()) {
appname_str = i18n("Unknown Application");
}
bool isPersistent = timeout == 0;
const int AVERAGE_WORD_LENGTH = 6;
const int WORD_PER_MINUTE = 250;
int count = summary.length() + body.length();
if (timeout <= 0) {
timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE;
timeout = 2000 + qMax(timeout, 3000);
}
const QString source = QStringLiteral("notification %1").arg(id);
const QString source = QStringLiteral("notification %1").arg(id);
QString bodyFinal = (partOf == 0 ? body : _body);
bodyFinal = bodyFinal.trimmed();
bodyFinal = bodyFinal.replace(QLatin1String("\n"), QLatin1String("<br/>"));
bodyFinal = bodyFinal.simplified();
bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>"));
bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&"));
bodyFinal.replace(QLatin1String("'"), QChar('\''));
Plasma::DataEngine::Data notificationData;
notificationData.insert(QStringLiteral("id"), QString::number(id));
bodyFinal = bodyFinal.simplified();
bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>"));
bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&"));
bodyFinal.replace(QLatin1String("'"), QChar('\''));
Plasma::DataEngine::Data notificationData;
notificationData.insert(QStringLiteral("id"), QString::number(id));
notificationData.insert(QStringLiteral("eventId"), eventId);
notificationData.insert(QStringLiteral("appName"), appname_str);
notificationData.insert(QStringLiteral("appIcon"), app_icon);
notificationData.insert(QStringLiteral("summary"), summary);
notificationData.insert(QStringLiteral("body"), bodyFinal);
notificationData.insert(QStringLiteral("actions"), actions);
notificationData.insert(QStringLiteral("isPersistent"), isPersistent);
notificationData.insert(QStringLiteral("expireTimeout"), timeout);
bool configurable = false;
if (!appRealName.isEmpty()) {
if (m_configurableApplications.contains(appRealName)) {
configurable = m_configurableApplications.value(appRealName);
} else {
QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals));
config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc")));
const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$"));
configurable = !config->groupList().filter(regexp).isEmpty();
m_configurableApplications.insert(appRealName, configurable);
}
}
notificationData.insert(QStringLiteral("appRealName"), appRealName);
notificationData.insert(QStringLiteral("configurable"), configurable);
QImage image;
if (hints.contains(QStringLiteral("image-data"))) {
QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
} else if (hints.contains(QStringLiteral("image_data"))) {
QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
} else if (hints.contains(QStringLiteral("image-path"))) {
QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString());
if (!path.isEmpty()) {
image.load(path);
}
} else if (hints.contains(QStringLiteral("image_path"))) {
QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString());
if (!path.isEmpty()) {
image.load(path);
}
} else if (hints.contains(QStringLiteral("icon_data"))) {
QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
}
notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image);
if (hints.contains(QStringLiteral("urgency"))) {
notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt());
}
setData(source, notificationData);
m_activeNotifications.insert(source, app_name + summary);
return id;
}
Commit Message:
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void set_socket_blocking(int s, int blocking)
{
int opts;
opts = fcntl(s, F_GETFL);
if (opts<0) APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
if(blocking)
opts &= ~O_NONBLOCK;
else opts |= O_NONBLOCK;
if (fcntl(s, F_SETFL, opts) < 0)
APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: DOMHighResTimeStamp PerformanceNavigationTiming::domContentLoadedEventEnd()
const {
const DocumentTiming* timing = GetDocumentTiming();
if (!timing)
return 0.0;
return Performance::MonotonicTimeToDOMHighResTimeStamp(
TimeOrigin(), timing->DomContentLoadedEventEnd(),
false /* allow_negative_value */);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <[email protected]>
Commit-Queue: Nicolás Peña Moreno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ,
krb5_db_entry **server_ptr, const char **status)
{
krb5_error_code retval;
krb5_principal *plist = NULL, *pl2;
krb5_data tmp;
krb5_db_entry *server = NULL;
*server_ptr = NULL;
assert(is_cross_tgs_principal(princ));
if ((retval = krb5_walk_realm_tree(kdc_context,
krb5_princ_realm(kdc_context, princ),
krb5_princ_component(kdc_context, princ, 1),
&plist, KRB5_REALM_BRANCH_CHAR))) {
goto cleanup;
}
/* move to the end */
for (pl2 = plist; *pl2; pl2++);
/* the first entry in this array is for krbtgt/local@local, so we
ignore it */
while (--pl2 > plist) {
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status);
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
if (retval == KRB5_KDB_NOENTRY)
continue;
else if (retval)
goto cleanup;
log_tgs_alt_tgt(kdc_context, server->princ);
*server_ptr = server;
server = NULL;
goto cleanup;
}
cleanup:
if (retval != 0)
*status = "UNKNOWN_SERVER";
krb5_free_realm_tree(kdc_context, plist);
krb5_db_free_principal(kdc_context, server);
return retval;
}
Commit Message: KDC null deref due to referrals [CVE-2013-1417]
An authenticated remote client can cause a KDC to crash by making a
valid TGS-REQ to a KDC serving a realm with a single-component name.
The process_tgs_req() function dereferences a null pointer because an
unusual failure condition causes a helper function to return success.
While attempting to provide cross-realm referrals for host-based
service principals, the find_referral_tgs() function could return a
TGS principal for a zero-length realm name (indicating that the
hostname in the service principal has no known realm associated with
it).
Subsequently, the find_alternate_tgs() function would attempt to
construct a path to this empty-string realm, and return success along
with a null pointer in its output parameter. This happens because
krb5_walk_realm_tree() returns a list of length one when it attempts
to construct a transit path between a single-component realm and the
empty-string realm. This list causes a loop in find_alternate_tgs()
to iterate over zero elements, resulting in the unexpected output of a
null pointer, which process_tgs_req() proceeds to dereference because
there is no error condition.
Add an error condition to find_referral_tgs() when
krb5_get_host_realm() returns an empty realm name. Also add an error
condition to find_alternate_tgs() to handle the length-one output from
krb5_walk_realm_tree().
The vulnerable configuration is not likely to arise in practice.
(Realm names that have a single component are likely to be test
realms.) Releases prior to krb5-1.11 are not vulnerable.
Thanks to Sol Jerome for reporting this problem.
CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
(cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0)
ticket: 7668
version_fixed: 1.11.4
status: resolved
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB))
return -EINVAL;
if (!vma->vm_file || !vma->vm_file->f_mapping
|| !vma->vm_file->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/* filesystem's fallocate may need to take i_mutex */
up_read(¤t->mm->mmap_sem);
error = do_fallocate(vma->vm_file,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
down_read(¤t->mm->mmap_sem);
return error;
}
Commit Message: mm: Hold a file reference in madvise_remove
Otherwise the code races with munmap (causing a use-after-free
of the vma) or with close (causing a use-after-free of the struct
file).
The bug was introduced by commit 90ed52ebe481 ("[PATCH] holepunch: fix
mmap_sem i_mutex deadlock")
Cc: Hugh Dickins <[email protected]>
Cc: Miklos Szeredi <[email protected]>
Cc: Badari Pulavarty <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: InputImeAPI::InputImeAPI(content::BrowserContext* context)
: browser_context_(context), extension_registry_observer_(this) {
extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
EventRouter* event_router = EventRouter::Get(browser_context_);
event_router->RegisterObserver(this, input_ime::OnFocus::kEventName);
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
content::NotificationService::AllSources());
}
Commit Message: Fix the regression caused by http://crrev.com/c/1288350.
Bug: 900124,856135
Change-Id: Ie11ad406bd1ea383dc2a83cc8661076309154865
Reviewed-on: https://chromium-review.googlesource.com/c/1317010
Reviewed-by: Lan Wei <[email protected]>
Commit-Queue: Shu Chen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605282}
CWE ID: CWE-416
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
Commit Message:
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent)
{
const rpki_rtr_pdu *pdu_header;
u_int pdu_type, pdu_len, hexdump;
const u_char *msg;
pdu_header = (const rpki_rtr_pdu *)tptr;
pdu_type = pdu_header->pdu_type;
pdu_len = EXTRACT_32BITS(pdu_header->length);
ND_TCHECK2(*tptr, pdu_len);
hexdump = FALSE;
ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u",
indent_string(8),
pdu_header->version,
tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type),
pdu_type, pdu_len));
switch (pdu_type) {
/*
* The following PDUs share the message format.
*/
case RPKI_RTR_SERIAL_NOTIFY_PDU:
case RPKI_RTR_SERIAL_QUERY_PDU:
case RPKI_RTR_END_OF_DATA_PDU:
msg = (const u_char *)(pdu_header + 1);
ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u",
indent_string(indent+2),
EXTRACT_16BITS(pdu_header->u.session_id),
EXTRACT_32BITS(msg)));
break;
/*
* The following PDUs share the message format.
*/
case RPKI_RTR_RESET_QUERY_PDU:
case RPKI_RTR_CACHE_RESET_PDU:
/*
* Zero payload PDUs.
*/
break;
case RPKI_RTR_CACHE_RESPONSE_PDU:
ND_PRINT((ndo, "%sSession ID: 0x%04x",
indent_string(indent+2),
EXTRACT_16BITS(pdu_header->u.session_id)));
break;
case RPKI_RTR_IPV4_PREFIX_PDU:
{
const rpki_rtr_pdu_ipv4_prefix *pdu;
pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr;
ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x",
indent_string(indent+2),
ipaddr_string(ndo, pdu->prefix),
pdu->prefix_length, pdu->max_length,
EXTRACT_32BITS(pdu->as), pdu->flags));
}
break;
case RPKI_RTR_IPV6_PREFIX_PDU:
{
const rpki_rtr_pdu_ipv6_prefix *pdu;
pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr;
ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x",
indent_string(indent+2),
ip6addr_string(ndo, pdu->prefix),
pdu->prefix_length, pdu->max_length,
EXTRACT_32BITS(pdu->as), pdu->flags));
}
break;
case RPKI_RTR_ERROR_REPORT_PDU:
{
const rpki_rtr_pdu_error_report *pdu;
u_int encapsulated_pdu_length, text_length, tlen, error_code;
pdu = (const rpki_rtr_pdu_error_report *)tptr;
encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length);
ND_TCHECK2(*tptr, encapsulated_pdu_length);
tlen = pdu_len;
error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code);
ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u",
indent_string(indent+2),
tok2str(rpki_rtr_error_codes, "Unknown", error_code),
error_code, encapsulated_pdu_length));
tptr += sizeof(*pdu);
tlen -= sizeof(*pdu);
/*
* Recurse if there is an encapsulated PDU.
*/
if (encapsulated_pdu_length &&
(encapsulated_pdu_length <= tlen)) {
ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4)));
if (rpki_rtr_pdu_print(ndo, tptr, indent+2))
goto trunc;
}
tptr += encapsulated_pdu_length;
tlen -= encapsulated_pdu_length;
/*
* Extract, trail-zero and print the Error message.
*/
text_length = 0;
if (tlen > 4) {
text_length = EXTRACT_32BITS(tptr);
tptr += 4;
tlen -= 4;
}
ND_TCHECK2(*tptr, text_length);
if (text_length && (text_length <= tlen )) {
ND_PRINT((ndo, "%sError text: ", indent_string(indent+2)));
if (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend))
goto trunc;
}
}
break;
default:
/*
* Unknown data, please hexdump.
*/
hexdump = TRUE;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo,tptr,"\n\t ", pdu_len);
}
return 0;
trunc:
return 1;
}
Commit Message: CVE-2017-13050/RPKI-Router: fix a few bugs
The decoder didn't properly check that the PDU length stored in the PDU
header is correct. The only check in place was in rpki_rtr_print() and it
tested whether the length is zero but that is not sufficient. Make all
necessary length and bounds checks, both generic and type-specific, in
rpki_rtr_pdu_print() and reduce rpki_rtr_print() to a simple loop.
This also fixes a minor bug and PDU type 0 (Serial Notify from RFC 6810
Section 5.2) is valid again.
In rpki_rtr_pdu_print() any protocol version was considered version 0,
fix it to skip the rest of input if the PDU protocol version is unknown.
Ibid, the PDU type 10 (Error Report from RFC 6810 Section 5.10) case
block didn't consider the "Length of Error Text" data element mandatory,
put it right.
Ibid, when printing an encapsulated PDU, give itself (via recursion)
respective buffer length to make it possible to tell whether the
encapsulated PDU fits. Do not recurse deeper than 2nd level.
Update prior RPKI-Router test cases that now stop to decode earlier
because of the stricter checks.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int fallback_migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page, enum migrate_mode mode)
{
if (PageDirty(page)) {
/* Only writeback pages in full synchronous migration */
if (mode != MIGRATE_SYNC)
return -EBUSY;
return writeout(mapping, page);
}
/*
* Buffers may be managed in a filesystem specific way.
* We must have no buffers or drop them.
*/
if (page_has_private(page) &&
!try_to_release_page(page, GFP_KERNEL))
return -EAGAIN;
return migrate_page(mapping, newpage, page, mode);
}
Commit Message: mm: migrate dirty page without clear_page_dirty_for_io etc
clear_page_dirty_for_io() has accumulated writeback and memcg subtleties
since v2.6.16 first introduced page migration; and the set_page_dirty()
which completed its migration of PageDirty, later had to be moderated to
__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.
No actual problems seen with this procedure recently, but if you look into
what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually
achieving, it turns out to be nothing more than moving the PageDirty flag,
and its NR_FILE_DIRTY stat from one zone to another.
It would be good to avoid a pile of irrelevant decrementations and
incrementations, and improper event counting, and unnecessary descent of
the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which
radix_tree_replace_slot() left in place anyway).
Do the NR_FILE_DIRTY movement, like the other stats movements, while
interrupts still disabled in migrate_page_move_mapping(); and don't even
bother if the zone is the same. Do the PageDirty movement there under
tree_lock too, where old page is frozen and newpage not yet visible:
bearing in mind that as soon as newpage becomes visible in radix_tree, an
un-page-locked set_page_dirty() might interfere (or perhaps that's just
not possible: anything doing so should already hold an additional
reference to the old page, preventing its migration; but play safe).
But we do still need to transfer PageDirty in migrate_page_copy(), for
those who don't go the mapping route through migrate_page_move_mapping().
Signed-off-by: Hugh Dickins <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: "Kirill A. Shutemov" <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Sasha Levin <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: htmlParseErr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar *str1, const xmlChar *str2)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_HTML, error,
XML_ERR_ERROR, NULL, 0,
(const char *) str1, (const char *) str2,
NULL, 0, 0,
msg, str1, str2);
if (ctxt != NULL)
ctxt->wellFormed = 0;
}
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 <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: NodeIterator::NodeIterator(PassRefPtrWillBeRawPtr<Node> rootNode, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter)
: NodeIteratorBase(rootNode, whatToShow, filter)
, m_referenceNode(root(), true)
{
root()->document().attachNodeIterator(this);
}
Commit Message: Fix detached Attr nodes interaction with NodeIterator
- Don't register NodeIterator to document when attaching to Attr node.
-- NodeIterator is registered to its document to receive updateForNodeRemoval notifications.
-- However it wouldn't make sense on Attr nodes, as they never have children.
BUG=572537
Review URL: https://codereview.chromium.org/1577213003
Cr-Commit-Position: refs/heads/master@{#369687}
CWE ID:
Target: 1
Example 2:
Code: DownloadItem::SafetyState DownloadItemImpl::GetSafetyState() const {
return safety_state_;
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CSoundFile::ExtraFinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const
{
if(GetType() == MOD_TYPE_XM)
{
if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldExtraFinePortaUpDown >> 4);
} else if(GetType() == MOD_TYPE_MT2)
{
if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown;
}
if(pChn->isFirstTick)
{
if ((pChn->nPeriod) && (param))
{
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
int oldPeriod = pChn->nPeriod;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideUpTable(this, param & 0x0F), 65536);
if(oldPeriod == pChn->nPeriod) pChn->nPeriod++;
} else
{
pChn->nPeriod -= (int)(param);
if (pChn->nPeriod < 1)
{
pChn->nPeriod = 1;
if(GetType() == MOD_TYPE_S3M)
{
pChn->nFadeOutVol = 0;
pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
}
}
}
}
}
Commit Message: [Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void LockScreenMediaControlsView::SetArtwork(
base::Optional<gfx::ImageSkia> img) {
if (!img.has_value()) {
session_artwork_->SetImage(nullptr);
return;
}
session_artwork_->SetImageSize(ScaleSizeToFitView(
img->size(), gfx::Size(kArtworkViewWidth, kArtworkViewHeight)));
session_artwork_->SetImage(*img);
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
Target: 1
Example 2:
Code: ImageBitmap* ImageBitmap::create(HTMLVideoElement* video,
Optional<IntRect> cropRect,
Document* document,
const ImageBitmapOptions& options) {
return new ImageBitmap(video, cropRect, document, options);
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx,
unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_HMAC_SHA256 *key = data(ctx);
unsigned int l;
size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and
* later */
sha_off = 0;
# if defined(STITCHED_CALL)
size_t aes_off = 0, blocks;
sha_off = SHA256_CBLOCK - key->md.num;
# endif
key->payload_length = NO_PAYLOAD_LENGTH;
if (len % AES_BLOCK_SIZE)
return 0;
if (ctx->encrypt) {
if (plen == NO_PAYLOAD_LENGTH)
plen = len;
else if (len !=
((plen + SHA256_DIGEST_LENGTH +
AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))
return 0;
else if (key->aux.tls_ver >= TLS1_1_VERSION)
iv = AES_BLOCK_SIZE;
# if defined(STITCHED_CALL)
/*
* Assembly stitch handles AVX-capable processors, but its
* performance is not optimal on AMD Jaguar, ~40% worse, for
* unknown reasons. Incidentally processor in question supports
* AVX, but not AMD-specific XOP extension, which can be used
* to identify it and avoid stitch invocation. So that after we
* establish that current CPU supports AVX, we even see if it's
* either even XOP-capable Bulldozer-based or GenuineIntel one.
*/
if (OPENSSL_ia32cap_P[1] & (1 << (60 - 32)) && /* AVX? */
((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */
| (OPENSSL_ia32cap_P[0] & (1<<30))) && /* "Intel CPU"? */
plen > (sha_off + iv) &&
(blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) {
SHA256_Update(&key->md, in + iv, sha_off);
(void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks,
ctx->iv, &key->md, in + iv + sha_off);
blocks *= SHA256_CBLOCK;
aes_off += blocks;
sha_off += blocks;
key->md.Nh += blocks >> 29;
key->md.Nl += blocks <<= 3;
if (key->md.Nl < (unsigned int)blocks)
key->md.Nh++;
} else {
sha_off = 0;
}
# endif
sha_off += iv;
SHA256_Update(&key->md, in + sha_off, plen - sha_off);
if (plen != len) { /* "TLS" mode of operation */
if (in != out)
memcpy(out + aes_off, in + aes_off, plen - aes_off);
/* calculate HMAC and append it to payload */
SHA256_Final(out + plen, &key->md);
key->md = key->tail;
SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH);
SHA256_Final(out + plen, &key->md);
/* pad the payload|hmac */
plen += SHA256_DIGEST_LENGTH;
for (l = len - plen - 1; plen < len; plen++)
out[plen] = l;
/* encrypt HMAC|padding at once */
aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,
&key->ks, ctx->iv, 1);
} else {
aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,
&key->ks, ctx->iv, 1);
}
} else {
union {
unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)];
unsigned char c[64 + SHA256_DIGEST_LENGTH];
} mac, *pmac;
/* arrange cache line alignment */
pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64));
/* decrypt HMAC|padding at once */
aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);
if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */
size_t inp_len, mask, j, i;
unsigned int res, maxpad, pad, bitlen;
int ret = 1;
union {
unsigned int u[SHA_LBLOCK];
unsigned char c[SHA256_CBLOCK];
} *data = (void *)key->md.data;
if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])
>= TLS1_1_VERSION)
iv = AES_BLOCK_SIZE;
if (len < (iv + SHA256_DIGEST_LENGTH + 1))
return 0;
/* omit explicit iv */
out += iv;
len -= iv;
/* figure out payload length */
pad = out[len - 1];
maxpad = len - (SHA256_DIGEST_LENGTH + 1);
maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);
maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);
maxpad &= 255;
inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1);
mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));
inp_len &= mask;
key->aux.tls_aad[plen - 1] = inp_len;
/* calculate HMAC */
key->md = key->head;
SHA256_Update(&key->md, key->aux.tls_aad, plen);
# if 1
len -= SHA256_DIGEST_LENGTH; /* amend mac */
if (len >= (256 + SHA256_CBLOCK)) {
j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK);
j += SHA256_CBLOCK - key->md.num;
SHA256_Update(&key->md, out, j);
out += j;
len -= j;
inp_len -= j;
}
/* but pretend as if we hashed padded payload */
bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */
# ifdef BSWAP4
bitlen = BSWAP4(bitlen);
# else
mac.c[0] = 0;
mac.c[1] = (unsigned char)(bitlen >> 16);
mac.c[2] = (unsigned char)(bitlen >> 8);
mac.c[3] = (unsigned char)bitlen;
bitlen = mac.u[0];
# endif
pmac->u[0] = 0;
pmac->u[1] = 0;
pmac->u[2] = 0;
pmac->u[3] = 0;
pmac->u[4] = 0;
pmac->u[5] = 0;
pmac->u[6] = 0;
pmac->u[7] = 0;
for (res = key->md.num, j = 0; j < len; j++) {
size_t c = out[j];
mask = (j - inp_len) >> (sizeof(j) * 8 - 8);
c &= mask;
c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));
data->c[res++] = (unsigned char)c;
if (res != SHA256_CBLOCK)
continue;
/* j is not incremented yet */
mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));
data->u[SHA_LBLOCK - 1] |= bitlen & mask;
sha256_block_data_order(&key->md, data, 1);
mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));
pmac->u[0] |= key->md.h[0] & mask;
pmac->u[1] |= key->md.h[1] & mask;
pmac->u[2] |= key->md.h[2] & mask;
pmac->u[3] |= key->md.h[3] & mask;
pmac->u[4] |= key->md.h[4] & mask;
pmac->u[5] |= key->md.h[5] & mask;
pmac->u[6] |= key->md.h[6] & mask;
pmac->u[7] |= key->md.h[7] & mask;
res = 0;
}
for (i = res; i < SHA256_CBLOCK; i++, j++)
data->c[i] = 0;
if (res > SHA256_CBLOCK - 8) {
mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));
data->u[SHA_LBLOCK - 1] |= bitlen & mask;
sha256_block_data_order(&key->md, data, 1);
mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
pmac->u[0] |= key->md.h[0] & mask;
pmac->u[1] |= key->md.h[1] & mask;
pmac->u[2] |= key->md.h[2] & mask;
pmac->u[3] |= key->md.h[3] & mask;
pmac->u[4] |= key->md.h[4] & mask;
pmac->u[5] |= key->md.h[5] & mask;
pmac->u[6] |= key->md.h[6] & mask;
pmac->u[7] |= key->md.h[7] & mask;
memset(data, 0, SHA256_CBLOCK);
j += 64;
}
data->u[SHA_LBLOCK - 1] = bitlen;
sha256_block_data_order(&key->md, data, 1);
mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
pmac->u[0] |= key->md.h[0] & mask;
pmac->u[1] |= key->md.h[1] & mask;
pmac->u[2] |= key->md.h[2] & mask;
pmac->u[3] |= key->md.h[3] & mask;
pmac->u[4] |= key->md.h[4] & mask;
pmac->u[5] |= key->md.h[5] & mask;
pmac->u[6] |= key->md.h[6] & mask;
pmac->u[7] |= key->md.h[7] & mask;
# ifdef BSWAP4
pmac->u[0] = BSWAP4(pmac->u[0]);
pmac->u[1] = BSWAP4(pmac->u[1]);
pmac->u[2] = BSWAP4(pmac->u[2]);
pmac->u[3] = BSWAP4(pmac->u[3]);
pmac->u[4] = BSWAP4(pmac->u[4]);
pmac->u[5] = BSWAP4(pmac->u[5]);
pmac->u[6] = BSWAP4(pmac->u[6]);
pmac->u[7] = BSWAP4(pmac->u[7]);
# else
for (i = 0; i < 8; i++) {
res = pmac->u[i];
pmac->c[4 * i + 0] = (unsigned char)(res >> 24);
pmac->c[4 * i + 1] = (unsigned char)(res >> 16);
pmac->c[4 * i + 2] = (unsigned char)(res >> 8);
pmac->c[4 * i + 3] = (unsigned char)res;
}
# endif
len += SHA256_DIGEST_LENGTH;
# else
SHA256_Update(&key->md, out, inp_len);
res = key->md.num;
SHA256_Final(pmac->c, &key->md);
{
unsigned int inp_blocks, pad_blocks;
/* but pretend as if we hashed padded payload */
inp_blocks =
1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
res += (unsigned int)(len - inp_len);
pad_blocks = res / SHA256_CBLOCK;
res %= SHA256_CBLOCK;
pad_blocks +=
1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
for (; inp_blocks < pad_blocks; inp_blocks++)
sha1_block_data_order(&key->md, data, 1);
}
# endif
key->md = key->tail;
SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH);
SHA256_Final(pmac->c, &key->md);
/* verify HMAC */
out += inp_len;
len -= inp_len;
# if 1
{
unsigned char *p =
out + len - 1 - maxpad - SHA256_DIGEST_LENGTH;
size_t off = out - p;
unsigned int c, cmask;
maxpad += SHA256_DIGEST_LENGTH;
for (res = 0, i = 0, j = 0; j < maxpad; j++) {
c = p[j];
cmask =
((int)(j - off - SHA256_DIGEST_LENGTH)) >>
(sizeof(int) * 8 - 1);
res |= (c ^ pad) & ~cmask; /* ... and padding */
cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);
res |= (c ^ pmac->c[i]) & cmask;
i += 1 & cmask;
}
maxpad -= SHA256_DIGEST_LENGTH;
res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
ret &= (int)~res;
}
# else
for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++)
res |= out[i] ^ pmac->c[i];
res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
ret &= (int)~res;
/* verify padding */
pad = (pad & ~res) | (maxpad & res);
out = out + len - 1 - pad;
for (res = 0, i = 0; i < pad; i++)
res |= out[i] ^ pad;
res = (0 - res) >> (sizeof(res) * 8 - 1);
ret &= (int)~res;
# endif
return ret;
} else {
SHA256_Update(&key->md, out, len);
}
}
return 1;
}
Commit Message:
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,
const int argc,const char **argv,Image **images,ExceptionInfo *exception)
{
ChannelType
channel;
const char
*option;
ImageInfo
*mogrify_info;
MagickStatusType
status;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
count,
index;
/*
Apply options to the image list.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image **) NULL);
assert((*images)->previous == (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
if ((argc <= 0) || (*argv == (char *) NULL))
return(MagickTrue);
mogrify_info=CloneImageInfo(image_info);
quantize_info=AcquireQuantizeInfo(mogrify_info);
channel=mogrify_info->channel;
status=MagickTrue;
for (i=0; i < (ssize_t) argc; i++)
{
if (*images == (Image *) NULL)
break;
option=argv[i];
if (IsCommandOption(option) == MagickFalse)
continue;
count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
count=MagickMax(count,0L);
if ((i+count) >= (ssize_t) argc)
break;
status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("affinity",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL);
InheritException(exception,&(*images)->exception);
break;
}
i++;
break;
}
if (LocaleCompare("append",option+1) == 0)
{
Image
*append_image;
(void) SyncImagesSettings(mogrify_info,*images);
append_image=AppendImages(*images,*option == '-' ? MagickTrue :
MagickFalse,exception);
if (append_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=append_image;
break;
}
if (LocaleCompare("average",option+1) == 0)
{
Image
*average_image;
/*
Average an image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
average_image=EvaluateImages(*images,MeanEvaluateOperator,
exception);
if (average_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=average_image;
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channel",option+1) == 0)
{
if (*option == '+')
{
channel=DefaultChannels;
break;
}
channel=(ChannelType) ParseChannelOption(argv[i+1]);
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
clut_image=RemoveFirstImageFromList(images);
if (clut_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) ClutImageChannel(image,channel,clut_image);
clut_image=DestroyImage(clut_image);
InheritException(exception,&image->exception);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
Image
*coalesce_image;
(void) SyncImagesSettings(mogrify_info,*images);
coalesce_image=CoalesceImages(*images,exception);
if (coalesce_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=coalesce_image;
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
Image
*combine_image;
(void) SyncImagesSettings(mogrify_info,*images);
combine_image=CombineImages(*images,channel,exception);
if (combine_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=combine_image;
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
const char
*option;
double
distortion;
Image
*difference_image,
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
reconstruct_image=RemoveFirstImageFromList(images);
if (reconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
metric=UndefinedMetric;
option=GetImageOption(image_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
difference_image=CompareImageChannels(image,reconstruct_image,
channel,metric,&distortion,exception);
if (difference_image == (Image *) NULL)
break;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=difference_image;
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
ComplexOperator
op;
Image
*complex_images;
(void) SyncImageSettings(mogrify_info,*images);
op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,
MagickFalse,argv[i+1]);
complex_images=ComplexImages(*images,op,exception);
if (complex_images == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=complex_images;
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
Image
*mask_image,
*composite_image,
*image;
RectangleInfo
geometry;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
composite_image=RemoveFirstImageFromList(images);
if (composite_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) TransformImage(&composite_image,(char *) NULL,
composite_image->geometry);
SetGeometry(composite_image,&geometry);
(void) ParseAbsoluteGeometry(composite_image->geometry,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,
&geometry);
mask_image=RemoveFirstImageFromList(images);
if (mask_image != (Image *) NULL)
{
if ((image->compose == DisplaceCompositeOp) ||
(image->compose == DistortCompositeOp))
{
/*
Merge Y displacement into X displacement image.
*/
(void) CompositeImage(composite_image,CopyGreenCompositeOp,
mask_image,0,0);
mask_image=DestroyImage(mask_image);
}
else
{
/*
Set a blending mask for the composition.
*/
if (image->mask != (Image *) NULL)
image->mask=DestroyImage(image->mask);
image->mask=mask_image;
(void) NegateImage(image->mask,MagickFalse);
}
}
(void) CompositeImageChannel(image,channel,image->compose,
composite_image,geometry.x,geometry.y);
if (mask_image != (Image *) NULL)
{
image->mask=DestroyImage(image->mask);
mask_image=image->mask;
}
composite_image=DestroyImage(composite_image);
InheritException(exception,&image->exception);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
(void) SyncImageSettings(mogrify_info,*images);
(void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=(*images);
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,argv[i+1],&geometry,
exception);
status=CopyImagePixels(*images,source_image,&geometry,&offset,
exception);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
Image
*deconstruct_image;
(void) SyncImagesSettings(mogrify_info,*images);
deconstruct_image=DeconstructImages(*images,exception);
if (deconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=deconstruct_image;
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
DeleteImages(images,"-1",exception);
else
DeleteImages(images,argv[i+1],exception);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
if (*option == '+')
{
quantize_info->dither=MagickFalse;
break;
}
quantize_info->dither=MagickTrue;
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,argv[i+1]);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
Image
*duplicate_images;
if (*option == '+')
duplicate_images=DuplicateImages(*images,1,"-1",exception);
else
{
const char
*p;
size_t
number_duplicates;
number_duplicates=(size_t) StringToLong(argv[i+1]);
p=strchr(argv[i+1],',');
if (p == (const char *) NULL)
duplicate_images=DuplicateImages(*images,number_duplicates,
"-1",exception);
else
duplicate_images=DuplicateImages(*images,number_duplicates,p,
exception);
}
AppendImageToList(images, duplicate_images);
(void) SyncImagesSettings(mogrify_info,*images);
break;
}
break;
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
Image
*evaluate_image;
MagickEvaluateOperator
op;
(void) SyncImageSettings(mogrify_info,*images);
op=(MagickEvaluateOperator) ParseCommandOption(
MagickEvaluateOptions,MagickFalse,argv[i+1]);
evaluate_image=EvaluateImages(*images,op,exception);
if (evaluate_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=evaluate_image;
break;
}
break;
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
Image
*fourier_image;
/*
Implements the discrete Fourier transform (DFT).
*/
(void) SyncImageSettings(mogrify_info,*images);
fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?
MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
Image
*flatten_image;
(void) SyncImagesSettings(mogrify_info,*images);
flatten_image=MergeImageLayers(*images,FlattenLayer,exception);
if (flatten_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=flatten_image;
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
Image
*fx_image;
(void) SyncImagesSettings(mogrify_info,*images);
fx_image=FxImageChannel(*images,channel,argv[i+1],exception);
if (fx_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=fx_image;
break;
}
break;
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
Image
*hald_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
hald_image=RemoveFirstImageFromList(images);
if (hald_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) HaldClutImageChannel(image,channel,hald_image);
hald_image=DestroyImage(hald_image);
InheritException(exception,&image->exception);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=image;
break;
}
break;
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*fourier_image,
*magnitude_image,
*phase_image;
/*
Implements the inverse fourier discrete Fourier transform (DFT).
*/
(void) SyncImagesSettings(mogrify_info,*images);
magnitude_image=RemoveFirstImageFromList(images);
phase_image=RemoveFirstImageFromList(images);
if (phase_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
fourier_image=InverseFourierTransformImage(magnitude_image,
phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*p,
*q;
index=0;
if (*option != '+')
index=(ssize_t) StringToLong(argv[i+1]);
p=RemoveLastImageFromList(images);
if (p == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
q=p;
if (index == 0)
PrependImageToList(images,q);
else
if (index == (ssize_t) GetImageListLength(*images))
AppendImageToList(images,q);
else
{
q=GetImageFromList(*images,index-1);
if (q == (Image *) NULL)
{
p=DestroyImage(p);
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
InsertImageInList(&q,p);
}
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
Image
*layers;
ImageLayerMethod
method;
(void) SyncImagesSettings(mogrify_info,*images);
layers=(Image *) NULL;
method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions,
MagickFalse,argv[i+1]);
switch (method)
{
case CoalesceLayer:
{
layers=CoalesceImages(*images,exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
layers=CompareImageLayers(*images,method,exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
layers=MergeImageLayers(*images,method,exception);
break;
}
case DisposeLayer:
{
layers=DisposeImages(*images,exception);
break;
}
case OptimizeImageLayer:
{
layers=OptimizeImageLayers(*images,exception);
break;
}
case OptimizePlusLayer:
{
layers=OptimizePlusImageLayers(*images,exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(*images,exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(images,exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(images,exception);
break;
}
case OptimizeLayer:
{
/*
General Purpose, GIF Animation Optimizer.
*/
layers=CoalesceImages(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
layers=OptimizeImageLayers(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
layers=(Image *) NULL;
OptimizeImageTransparency(*images,exception);
InheritException(exception,&(*images)->exception);
(void) RemapImages(quantize_info,*images,(Image *) NULL);
break;
}
case CompositeLayer:
{
CompositeOperator
compose;
Image
*source;
RectangleInfo
geometry;
/*
Split image sequence at the first 'NULL:' image.
*/
source=(*images);
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{
/*
Separate the two lists, junk the null: image.
*/
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
status=MagickFalse;
break;
}
/*
Adjust offset with gravity and virtual canvas.
*/
SetGeometry(*images,&geometry);
(void) ParseAbsoluteGeometry((*images)->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry((*images)->page.width != 0 ?
(*images)->page.width : (*images)->columns,
(*images)->page.height != 0 ? (*images)->page.height :
(*images)->rows,(*images)->gravity,&geometry);
compose=OverCompositeOp;
option=GetImageOption(mogrify_info,"compose");
if (option != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,option);
CompositeLayers(*images,compose,source,geometry.x,geometry.y,
exception);
source=DestroyImageList(source);
break;
}
}
if (layers == (Image *) NULL)
break;
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
break;
}
break;
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL);
InheritException(exception,&(*images)->exception);
break;
}
i++;
break;
}
if (LocaleCompare("maximum",option+1) == 0)
{
Image
*maximum_image;
/*
Maximum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);
if (maximum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=maximum_image;
break;
}
if (LocaleCompare("minimum",option+1) == 0)
{
Image
*minimum_image;
/*
Minimum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);
if (minimum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=minimum_image;
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
(void) SyncImagesSettings(mogrify_info,*images);
morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),
exception);
if (morph_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
Image
*mosaic_image;
(void) SyncImagesSettings(mogrify_info,*images);
mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);
if (mosaic_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=mosaic_image;
break;
}
break;
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
char
*args,
token[MaxTextExtent];
const char
*p;
double
*arguments;
Image
*polynomial_image;
register ssize_t
x;
size_t
number_arguments;
/*
Polynomial image.
*/
(void) SyncImageSettings(mogrify_info,*images);
args=InterpretImageProperties(mogrify_info,*images,argv[i+1]);
InheritException(exception,&(*images)->exception);
if (args == (char *) NULL)
break;
p=(char *) args;
for (x=0; *p != '\0'; x++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
}
number_arguments=(size_t) x;
arguments=(double *) AcquireQuantumMemory(number_arguments,
sizeof(*arguments));
if (arguments == (double *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed",(*images)->filename);
(void) memset(arguments,0,number_arguments*
sizeof(*arguments));
p=(char *) args;
for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
arguments[x]=StringToDouble(token,(char **) NULL);
}
args=DestroyString(args);
polynomial_image=PolynomialImageChannel(*images,channel,
number_arguments >> 1,arguments,exception);
arguments=(double *) RelinquishMagickMemory(arguments);
if (polynomial_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=polynomial_image;
break;
}
if (LocaleCompare("print",option+1) == 0)
{
char
*string;
(void) SyncImagesSettings(mogrify_info,*images);
string=InterpretImageProperties(mogrify_info,*images,argv[i+1]);
if (string == (char *) NULL)
break;
InheritException(exception,&(*images)->exception);
(void) FormatLocaleFile(stdout,"%s",string);
string=DestroyString(string);
}
if (LocaleCompare("process",option+1) == 0)
{
char
**arguments;
int
j,
number_arguments;
(void) SyncImagesSettings(mogrify_info,*images);
arguments=StringToArgv(argv[i+1],&number_arguments);
if (arguments == (char **) NULL)
break;
if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))
{
char
breaker,
quote,
*token;
const char
*arguments;
int
next,
status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg".
*/
length=strlen(argv[i+1]);
token=(char *) NULL;
if (~length >= (MaxTextExtent-1))
token=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
arguments=argv[i+1];
token_info=AcquireTokenInfo();
status=Tokenizer(token_info,0,token,length,arguments,"","=",
"\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (status == 0)
{
const char
*argv;
argv=(&(arguments[next]));
(void) InvokeDynamicImageFilter(token,&(*images),1,&argv,
exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&(*images),
number_arguments-2,(const char **) arguments+2,exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
break;
}
case 'r':
{
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(images);
InheritException(exception,&(*images)->exception);
break;
}
break;
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
Image
*smush_image;
ssize_t
offset;
(void) SyncImagesSettings(mogrify_info,*images);
offset=(ssize_t) StringToLong(argv[i+1]);
smush_image=SmushImages(*images,*option == '-' ? MagickTrue :
MagickFalse,offset,exception);
if (smush_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=smush_image;
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*u,
*v;
ssize_t
swap_index;
index=(-1);
swap_index=(-2);
if (*option != '+')
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(argv[i+1],&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(*images,index);
q=GetImageFromList(*images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",(*images)->filename);
status=MagickFalse;
break;
}
if (p == q)
break;
u=CloneImage(p,0,0,MagickTrue,exception);
if (u == (Image *) NULL)
break;
v=CloneImage(q,0,0,MagickTrue,exception);
if (v == (Image *) NULL)
{
u=DestroyImage(u);
break;
}
ReplaceImageInList(&p,v);
ReplaceImageInList(&q,u);
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("write",option+1) == 0)
{
char
key[MaxTextExtent];
Image
*write_images;
ImageInfo
*write_info;
(void) SyncImagesSettings(mogrify_info,*images);
(void) FormatLocaleString(key,MaxTextExtent,"cache:%s",argv[i+1]);
(void) DeleteImageRegistry(key);
write_images=(*images);
if (*option == '+')
write_images=CloneImageList(*images,exception);
write_info=CloneImageInfo(mogrify_info);
status&=WriteImages(write_info,write_images,argv[i+1],exception);
write_info=DestroyImageInfo(write_info);
if (*option == '+')
write_images=DestroyImageList(write_images);
break;
}
break;
}
default:
break;
}
i+=count;
}
quantize_info=DestroyQuantizeInfo(quantize_info);
mogrify_info=DestroyImageInfo(mogrify_info);
status&=MogrifyImageInfo(image_info,argc,argv,exception);
return(status != 0 ? MagickTrue : MagickFalse);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1623
CWE ID: CWE-399
Target: 1
Example 2:
Code: void ImageInputType::reattachFallbackContent()
{
if (element().document().inStyleRecalc())
element().reattach();
else
element().lazyReattachIfAttached();
}
Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree.
Once the fallback shadow tree was created, it was never recreated even if
ensurePrimaryContent was called. Such situation happens by updating |src|
attribute.
BUG=589838
Review URL: https://codereview.chromium.org/1732753004
Cr-Commit-Position: refs/heads/master@{#377804}
CWE ID: CWE-361
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int kvm_iommu_unmap_memslots(struct kvm *kvm)
{
int idx;
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
idx = srcu_read_lock(&kvm->srcu);
slots = kvm_memslots(kvm);
kvm_for_each_memslot(memslot, slots)
kvm_iommu_put_pages(kvm, memslot->base_gfn, memslot->npages);
srcu_read_unlock(&kvm->srcu, idx);
return 0;
}
Commit Message: KVM: unmap pages from the iommu when slots are removed
commit 32f6daad4651a748a58a3ab6da0611862175722f upstream.
We've been adding new mappings, but not destroying old mappings.
This can lead to a page leak as pages are pinned using
get_user_pages, but only unpinned with put_page if they still
exist in the memslots list on vm shutdown. A memslot that is
destroyed while an iommu domain is enabled for the guest will
therefore result in an elevated page reference count that is
never cleared.
Additionally, without this fix, the iommu is only programmed
with the first translation for a gpa. This can result in
peer-to-peer errors if a mapping is destroyed and replaced by a
new mapping at the same gpa as the iommu will still be pointing
to the original, pinned memory address.
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool NavigationControllerImpl::RendererDidNavigate(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
LoadCommittedDetails* details,
bool is_navigation_within_page,
NavigationHandleImpl* navigation_handle) {
is_initial_navigation_ = false;
bool overriding_user_agent_changed = false;
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->GetURL();
details->previous_entry_index = GetLastCommittedEntryIndex();
if (pending_entry_ &&
pending_entry_->GetIsOverridingUserAgent() !=
GetLastCommittedEntry()->GetIsOverridingUserAgent())
overriding_user_agent_changed = true;
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
bool was_restored = false;
DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
pending_entry_->restore_type() != RestoreType::NONE);
if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) {
pending_entry_->set_restore_type(RestoreType::NONE);
was_restored = true;
}
details->did_replace_entry = params.should_replace_current_entry;
details->type = ClassifyNavigation(rfh, params);
details->is_same_document = is_navigation_within_page;
if (PendingEntryMatchesHandle(navigation_handle)) {
if (pending_entry_->reload_type() != ReloadType::NONE) {
last_committed_reload_type_ = pending_entry_->reload_type();
last_committed_reload_time_ =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
} else if (!pending_entry_->is_renderer_initiated() ||
params.gesture == NavigationGestureUser) {
last_committed_reload_type_ = ReloadType::NONE;
last_committed_reload_time_ = base::Time();
}
}
switch (details->type) {
case NAVIGATION_TYPE_NEW_PAGE:
RendererDidNavigateToNewPage(rfh, params, details->is_same_document,
details->did_replace_entry,
navigation_handle);
break;
case NAVIGATION_TYPE_EXISTING_PAGE:
details->did_replace_entry = details->is_same_document;
RendererDidNavigateToExistingPage(rfh, params, details->is_same_document,
was_restored, navigation_handle);
break;
case NAVIGATION_TYPE_SAME_PAGE:
RendererDidNavigateToSamePage(rfh, params, navigation_handle);
break;
case NAVIGATION_TYPE_NEW_SUBFRAME:
RendererDidNavigateNewSubframe(rfh, params, details->is_same_document,
details->did_replace_entry);
break;
case NAVIGATION_TYPE_AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(rfh, params)) {
NotifyEntryChanged(GetLastCommittedEntry());
return false;
}
break;
case NAVIGATION_TYPE_NAV_IGNORE:
if (pending_entry_) {
DiscardNonCommittedEntries();
delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
return false;
default:
NOTREACHED();
}
base::Time timestamp =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DVLOG(1) << "Navigation finished at (smoothed) timestamp "
<< timestamp.ToInternalValue();
DiscardNonCommittedEntriesInternal();
DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
NavigationEntryImpl* active_entry = GetLastCommittedEntry();
active_entry->SetTimestamp(timestamp);
active_entry->SetHttpStatusCode(params.http_status_code);
FrameNavigationEntry* frame_entry =
active_entry->GetFrameEntry(rfh->frame_tree_node());
if (frame_entry) {
frame_entry->SetPageState(params.page_state);
frame_entry->set_redirect_chain(params.redirects);
}
if (!rfh->GetParent() &&
IsBlockedNavigation(navigation_handle->GetNetErrorCode())) {
DCHECK(params.url_is_unreachable);
active_entry->SetURL(GURL(url::kAboutBlankURL));
active_entry->SetVirtualURL(params.url);
if (frame_entry) {
frame_entry->SetPageState(
PageState::CreateFromURL(active_entry->GetURL()));
}
}
size_t redirect_chain_size = 0;
for (size_t i = 0; i < params.redirects.size(); ++i) {
redirect_chain_size += params.redirects[i].spec().length();
}
UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
active_entry->ResetForCommit(frame_entry);
if (!rfh->GetParent())
CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
active_entry->SetBindings(rfh->GetEnabledBindings());
details->entry = active_entry;
details->is_main_frame = !rfh->GetParent();
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details);
if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
navigation_handle->GetNetErrorCode() == net::OK) {
UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus",
!!active_entry->GetSSL().certificate);
}
if (overriding_user_agent_changed)
delegate_->UpdateOverridingUserAgent();
int nav_entry_id = active_entry->GetUniqueID();
for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes())
node->current_frame_host()->set_nav_entry_id(nav_entry_id);
return true;
}
Commit Message: Don't update PageState for a SiteInstance mismatch.
BUG=766262
TEST=See bug for repro.
Change-Id: Ifb087b687acd40d8963ef436c9ea82ca2d960117
Reviewed-on: https://chromium-review.googlesource.com/674808
Commit-Queue: Charlie Reis (OOO until 9/25) <[email protected]>
Reviewed-by: Łukasz Anforowicz <[email protected]>
Cr-Commit-Position: refs/heads/master@{#503297}
CWE ID:
Target: 1
Example 2:
Code: void DXVAVideoDecodeAccelerator::NotifyPictureReady(
const media::Picture& picture) {
if (state_ != kUninitialized && client_)
client_->PictureReady(picture);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual bool connect(
const char *uri, const KeyedVector<String8, String8> *headers) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
String16 tmp(uri);
data.writeString16(tmp);
tmp = String16("");
if (headers != NULL) {
for (size_t i = 0; i < headers->size(); ++i) {
String16 key(headers->keyAt(i).string());
String16 val(headers->valueAt(i).string());
tmp.append(key);
tmp.append(String16(": "));
tmp.append(val);
tmp.append(String16("\r\n"));
}
}
data.writeString16(tmp);
remote()->transact(CONNECT, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
sp<IBinder> binder = reply.readStrongBinder();
mMemory = interface_cast<IMemory>(binder);
return mMemory != NULL;
}
Commit Message: Add some sanity checks
Bug: 19400722
Change-Id: Ib3afdf73fd4647eeea5721c61c8b72dbba0647f6
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long long CuePoint::GetTimeCode() const
{
return m_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: gst_asf_demux_chain_headers (GstASFDemux * demux)
{
AsfObject obj;
guint8 *header_data, *data = NULL;
const guint8 *cdata = NULL;
guint64 header_size;
GstFlowReturn flow = GST_FLOW_OK;
cdata = (guint8 *) gst_adapter_map (demux->adapter, ASF_OBJECT_HEADER_SIZE);
if (cdata == NULL)
goto need_more_data;
if (!asf_demux_peek_object (demux, cdata, ASF_OBJECT_HEADER_SIZE, &obj, TRUE))
goto parse_failed;
if (obj.id != ASF_OBJ_HEADER)
goto wrong_type;
GST_LOG_OBJECT (demux, "header size = %u", (guint) obj.size);
/* + 50 for non-packet data at beginning of ASF_OBJ_DATA */
if (gst_adapter_available (demux->adapter) < obj.size + 50)
goto need_more_data;
data = gst_adapter_take (demux->adapter, obj.size + 50);
header_data = data;
header_size = obj.size;
flow = gst_asf_demux_process_object (demux, &header_data, &header_size);
if (flow != GST_FLOW_OK)
goto parse_failed;
/* calculate where the packet data starts */
demux->data_offset = obj.size + 50;
/* now parse the beginning of the ASF_OBJ_DATA object */
if (!gst_asf_demux_parse_data_object_start (demux, data + obj.size))
goto wrong_type;
if (demux->num_streams == 0)
goto no_streams;
g_free (data);
return GST_FLOW_OK;
/* NON-FATAL */
need_more_data:
{
GST_LOG_OBJECT (demux, "not enough data in adapter yet");
return GST_FLOW_OK;
}
/* ERRORS */
wrong_type:
{
GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE, (NULL),
("This doesn't seem to be an ASF file"));
g_free (data);
return GST_FLOW_ERROR;
}
no_streams:
parse_failed:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("header parsing failed, or no streams found, flow = %s",
gst_flow_get_name (flow)));
g_free (data);
return GST_FLOW_ERROR;
}
}
Commit Message: asfdemux: Check that we have enough data available before parsing bool/uint extended content descriptors
https://bugzilla.gnome.org/show_bug.cgi?id=777955
CWE ID: CWE-125
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: addSelectOption(FormSelectOption *fso, Str value, Str label, int chk)
{
FormSelectOptionItem *o;
o = New(FormSelectOptionItem);
if (value == NULL)
value = label;
o->value = value;
Strremovefirstspaces(label);
Strremovetrailingspaces(label);
o->label = label;
o->checked = chk;
o->next = NULL;
if (fso->first == NULL)
fso->first = fso->last = o;
else {
fso->last->next = o;
fso->last = o;
}
}
Commit Message: Prevent invalid columnPos() call in formUpdateBuffer()
Bug-Debian: https://github.com/tats/w3m/issues/89
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
assert(reactor != NULL);
reactor->run_thread = pthread_self();
reactor->is_running = true;
struct epoll_event events[MAX_EVENTS];
for (int i = 0; iterations == 0 || i < iterations; ++i) {
pthread_mutex_lock(&reactor->list_lock);
list_clear(reactor->invalidation_list);
pthread_mutex_unlock(&reactor->list_lock);
int ret;
do {
ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
for (int j = 0; j < ret; ++j) {
if (events[j].data.ptr == NULL) {
eventfd_t value;
eventfd_read(reactor->event_fd, &value);
reactor->is_running = false;
return REACTOR_STATUS_STOP;
}
reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
pthread_mutex_lock(&reactor->list_lock);
if (list_contains(reactor->invalidation_list, object)) {
pthread_mutex_unlock(&reactor->list_lock);
continue;
}
pthread_mutex_lock(&object->lock);
pthread_mutex_unlock(&reactor->list_lock);
reactor->object_removed = false;
if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
object->read_ready(object->context);
if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
object->write_ready(object->context);
pthread_mutex_unlock(&object->lock);
if (reactor->object_removed) {
pthread_mutex_destroy(&object->lock);
osi_free(object);
}
}
}
reactor->is_running = false;
return REACTOR_STATUS_DONE;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p, AVPacket *avpkt)
{
AVDictionary *metadata = NULL;
uint32_t tag, length;
int decode_next_dat = 0;
int ret;
for (;;) {
length = bytestream2_get_bytes_left(&s->gb);
if (length <= 0) {
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
if (!(s->state & PNG_IDAT))
return 0;
else
goto exit_loop;
}
av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
if ( s->state & PNG_ALLIMAGE
&& avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
goto exit_loop;
ret = AVERROR_INVALIDDATA;
goto fail;
}
length = bytestream2_get_be32(&s->gb);
if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
tag = bytestream2_get_le32(&s->gb);
if (avctx->debug & FF_DEBUG_STARTCODE)
av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
(tag & 0xff),
((tag >> 8) & 0xff),
((tag >> 16) & 0xff),
((tag >> 24) & 0xff), length);
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
switch(tag) {
case MKTAG('I', 'H', 'D', 'R'):
case MKTAG('p', 'H', 'Y', 's'):
case MKTAG('t', 'E', 'X', 't'):
case MKTAG('I', 'D', 'A', 'T'):
case MKTAG('t', 'R', 'N', 'S'):
break;
default:
goto skip_tag;
}
}
switch (tag) {
case MKTAG('I', 'H', 'D', 'R'):
if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
goto fail;
break;
case MKTAG('p', 'H', 'Y', 's'):
if ((ret = decode_phys_chunk(avctx, s)) < 0)
goto fail;
break;
case MKTAG('f', 'c', 'T', 'L'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
goto fail;
decode_next_dat = 1;
break;
case MKTAG('f', 'd', 'A', 'T'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if (!decode_next_dat) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_get_be32(&s->gb);
length -= 4;
/* fallthrough */
case MKTAG('I', 'D', 'A', 'T'):
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
goto skip_tag;
if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
goto fail;
break;
case MKTAG('P', 'L', 'T', 'E'):
if (decode_plte_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'R', 'N', 'S'):
if (decode_trns_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'E', 'X', 't'):
if (decode_text_chunk(s, length, 0, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('z', 'T', 'X', 't'):
if (decode_text_chunk(s, length, 1, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('s', 'T', 'E', 'R'): {
int mode = bytestream2_get_byte(&s->gb);
AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
if (!stereo3d)
goto fail;
if (mode == 0 || mode == 1) {
stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
} else {
av_log(avctx, AV_LOG_WARNING,
"Unknown value in sTER chunk (%d)\n", mode);
}
bytestream2_skip(&s->gb, 4); /* crc */
break;
}
case MKTAG('I', 'E', 'N', 'D'):
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_skip(&s->gb, 4); /* crc */
goto exit_loop;
default:
/* skip tag */
skip_tag:
bytestream2_skip(&s->gb, length + 4);
break;
}
}
exit_loop:
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (s->bits_per_pixel <= 4)
handle_small_bpp(s, p);
/* apply transparency if needed */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
size_t raw_bpp = s->bpp - byte_depth;
unsigned x, y;
for (y = 0; y < s->height; ++y) {
uint8_t *row = &s->image_buf[s->image_linesize * y];
/* since we're updating in-place, we have to go from right to left */
for (x = s->width; x > 0; --x) {
uint8_t *pixel = &row[s->bpp * (x - 1)];
memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
memset(&pixel[raw_bpp], 0, byte_depth);
} else {
memset(&pixel[raw_bpp], 0xff, byte_depth);
}
}
}
}
/* handle P-frames only if a predecessor frame is available */
if (s->last_picture.f->data[0]) {
if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
&& s->last_picture.f->width == p->width
&& s->last_picture.f->height== p->height
&& s->last_picture.f->format== p->format
) {
if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
handle_p_frame_png(s, p);
else if (CONFIG_APNG_DECODER &&
avctx->codec_id == AV_CODEC_ID_APNG &&
(ret = handle_p_frame_apng(avctx, s, p)) < 0)
goto fail;
}
}
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
av_frame_set_metadata(p, metadata);
metadata = NULL;
return 0;
fail:
av_dict_free(&metadata);
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
return ret;
}
Commit Message: avcodec/pngdec: Fix off by 1 size in decode_zbuf()
Fixes out of array access
Fixes: 444/fuzz-2-ffmpeg_VIDEO_AV_CODEC_ID_PNG_fuzzer
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-787
Target: 0
Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ih264d_init_decoder(void * ps_dec_params)
{
dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params;
dec_slice_params_t *ps_cur_slice;
pocstruct_t *ps_prev_poc, *ps_cur_poc;
/* Free any dynamic buffers that are allocated */
ih264d_free_dynamic_bufs(ps_dec);
ps_cur_slice = ps_dec->ps_cur_slice;
ps_dec->init_done = 0;
ps_dec->u4_num_cores = 1;
ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0;
ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE;
ps_dec->u4_app_disable_deblk_frm = 0;
ps_dec->i4_degrade_type = 0;
ps_dec->i4_degrade_pics = 0;
ps_dec->i4_app_skip_mode = IVD_SKIP_NONE;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
memset(ps_dec->ps_pps, 0,
((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS));
memset(ps_dec->ps_sps, 0,
((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS));
/* Initialization of function pointers ih264d_deblock_picture function*/
ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff;
ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff;
ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec;
ps_dec->u4_num_fld_in_frm = 0;
ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec;
/* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/
ps_dec->ps_sei->u1_is_valid = 0;
/* decParams Initializations */
ps_dec->ps_cur_pps = NULL;
ps_dec->ps_cur_sps = NULL;
ps_dec->u1_init_dec_flag = 0;
ps_dec->u1_first_slice_in_stream = 1;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u4_app_disp_width = 0;
ps_dec->i4_header_decoded = 0;
ps_dec->u4_total_frames_decoded = 0;
ps_dec->i4_error_code = 0;
ps_dec->i4_content_type = -1;
ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0;
ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS;
ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME;
ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
ps_dec->u1_pr_sl_type = 0xFF;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
ps_dec->u2_total_mbs_coded = 0;
/* POC initializations */
ps_prev_poc = &ps_dec->s_prev_pic_poc;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0] = 0;
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1] = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count =
0;
ps_prev_poc->i4_bottom_field_order_count =
ps_cur_poc->i4_bottom_field_order_count = 0;
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0;
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = 0;
ps_dec->i4_max_poc = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->u1_recon_mb_grp = 4;
/* Field PIC initializations */
ps_dec->u1_second_field = 0;
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
/* Set the cropping parameters as zero */
ps_dec->u2_crop_offset_y = 0;
ps_dec->u2_crop_offset_uv = 0;
/* The Initial Frame Rate Info is not Present */
ps_dec->i4_vui_frame_rate = -1;
ps_dec->i4_pic_type = -1;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
ps_dec->u1_res_changed = 0;
ps_dec->u1_frame_decoded_flag = 0;
/* Set the default frame seek mask mode */
ps_dec->u4_skip_frm_mask = SKIP_NONE;
/********************************************************/
/* Initialize CAVLC residual decoding function pointers */
/********************************************************/
ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1;
ps_dec->pf_cavlc_4x4res_block[1] =
ih264d_cavlc_4x4res_block_totalcoeff_2to10;
ps_dec->pf_cavlc_4x4res_block[2] =
ih264d_cavlc_4x4res_block_totalcoeff_11to16;
ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7;
ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8;
ps_dec->pf_cavlc_parse_8x8block[0] =
ih264d_cavlc_parse_8x8block_none_available;
ps_dec->pf_cavlc_parse_8x8block[1] =
ih264d_cavlc_parse_8x8block_left_available;
ps_dec->pf_cavlc_parse_8x8block[2] =
ih264d_cavlc_parse_8x8block_top_available;
ps_dec->pf_cavlc_parse_8x8block[3] =
ih264d_cavlc_parse_8x8block_both_available;
/***************************************************************************/
/* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */
/***************************************************************************/
ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice;
ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice;
ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice;
ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice;
ps_dec->pf_fill_bs_xtra_left_edge[0] =
ih264d_fill_bs_xtra_left_edge_cur_frm;
ps_dec->pf_fill_bs_xtra_left_edge[1] =
ih264d_fill_bs_xtra_left_edge_cur_fld;
/* Initialize Reference Pic Buffers */
ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr);
ps_dec->u2_prv_frame_num = 0;
ps_dec->u1_top_bottom_decoded = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table;
ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0];
ps_dec->pi1_left_ref_idx_ctxt_inc =
&ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0];
ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb;
/* ! */
/* Initializing flush frame u4_flag */
ps_dec->u1_flushfrm = 0;
{
ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec;
ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec;
}
memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t));
memset(ps_dec->u4_disp_buf_mapping, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
memset(ps_dec->u4_disp_buf_to_be_freed, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
ih264d_init_arch(ps_dec);
ih264d_init_function_ptr(ps_dec);
ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
ps_dec->init_done = 1;
}
Commit Message: Decoder: Memset few structures to zero to handle error clips
Bug: 27907656
Change-Id: I671d135dd5c324c39b4ede990b7225d52ba882cd
CWE ID: CWE-20
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.