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: MediaStreamDispatcherHost::MediaStreamDispatcherHost(
int render_process_id,
int render_frame_id,
MediaStreamManager* media_stream_manager)
: render_process_id_(render_process_id),
render_frame_id_(render_frame_id),
media_stream_manager_(media_stream_manager),
salt_and_origin_callback_(
base::BindRepeating(&GetMediaDeviceSaltAndOrigin)),
weak_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
bindings_.set_connection_error_handler(
base::Bind(&MediaStreamDispatcherHost::CancelAllRequests,
weak_factory_.GetWeakPtr()));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189
Target: 1
Example 2:
Code: FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
switch (type) {
case blink::WebIconURL::kTypeFavicon:
return FaviconURL::IconType::kFavicon;
case blink::WebIconURL::kTypeTouch:
return FaviconURL::IconType::kTouchIcon;
case blink::WebIconURL::kTypeTouchPrecomposed:
return FaviconURL::IconType::kTouchPrecomposedIcon;
case blink::WebIconURL::kTypeInvalid:
return FaviconURL::IconType::kInvalid;
}
NOTREACHED();
return FaviconURL::IconType::kInvalid;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: filesystem_create_create_luks_device_completed_cb (DBusGMethodInvocation *context,
Device *device,
gboolean job_was_cancelled,
int status,
const char *stderr,
const char *stdout,
gpointer user_data)
{
MkfsLuksData *data = user_data;
/* poke the kernel so we can reread the data (new uuid etc.) */
device_generate_kernel_change_event (device);
if (WEXITSTATUS (status) == 0 && !job_was_cancelled)
{
/* OK! So we've got ourselves an luks device. Let's set it up so we can create a file
* system. Sit and wait for the change event to appear so we can setup with the right UUID.
*/
data->device_changed_signal_handler_id
= g_signal_connect_after (device->priv->daemon,
"device-changed",
(GCallback) filesystem_create_wait_for_luks_device_changed_cb,
mkfse_data_ref (data));
/* set up timeout for error reporting if waiting failed
*
* (the signal handler and the timeout handler share the ref to data
* as one will cancel the other)
*/
data->device_changed_timeout_id = g_timeout_add (10 * 1000,
filesystem_create_wait_for_luks_device_not_seen_cb,
data);
}
else
{
if (job_was_cancelled)
{
throw_error (context, ERROR_CANCELLED, "Job was cancelled");
}
else
{
throw_error (context,
ERROR_FAILED,
"Error creating file system: cryptsetup exited with exit code %d: %s",
WEXITSTATUS (status),
stderr);
}
}
}
Commit Message:
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: static void v9fs_read(void *opaque)
{
int32_t fid;
uint64_t off;
ssize_t err = 0;
int32_t count = 0;
size_t offset = 7;
uint32_t max_count;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_DIR) {
if (off == 0) {
v9fs_co_rewinddir(pdu, fidp);
}
count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
if (count < 0) {
err = count;
goto out;
}
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
} else if (fidp->fid_type == P9_FID_FILE) {
QEMUIOVector qiov_full;
QEMUIOVector qiov;
int32_t len;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
count += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out;
}
} while (count < max_count && len > 0);
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
qemu_iovec_destroy(&qiov);
qemu_iovec_destroy(&qiov_full);
} else if (fidp->fid_type == P9_FID_XATTR) {
} else {
err = -EINVAL;
}
trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int ttusbdecfe_dvbt_get_tune_settings(struct dvb_frontend* fe,
struct dvb_frontend_tune_settings* fesettings)
{
fesettings->min_delay_ms = 1500;
/* Drift compensation makes no sense for DVB-T */
fesettings->step_size = 0;
fesettings->max_drift = 0;
return 0;
}
Commit Message: [media] ttusb-dec: buffer overflow in ioctl
We need to add a limit check here so we don't overflow the buffer.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PP_Resource Resource::GetReferenceNoAddRef() const {
return resource_id_;
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
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: JSValue JSDirectoryEntry::getDirectory(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
if (exec->hadException())
return jsUndefined();
int argsCount = exec->argumentCount();
if (argsCount <= 1) {
imp->getDirectory(path);
return jsUndefined();
}
RefPtr<WebKitFlags> flags;
if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
JSObject* object = exec->argument(1).getObject();
flags = WebKitFlags::create();
JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
flags->setCreate(jsCreate.toBoolean(exec));
JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
flags->setExclusive(jsExclusive.toBoolean(exec));
}
if (exec->hadException())
return jsUndefined();
RefPtr<EntryCallback> successCallback;
if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
if (!exec->argument(2).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
}
RefPtr<ErrorCallback> errorCallback;
if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
if (!exec->argument(3).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
}
imp->getDirectory(path, flags, successCallback, errorCallback);
return 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 void ehci_free_queue(EHCIQueue *q, const char *warn)
{
EHCIQueueHead *head = q->async ? &q->ehci->aqueues : &q->ehci->pqueues;
int cancelled;
trace_usb_ehci_queue_action(q, "free");
cancelled = ehci_cancel_queue(q);
if (warn && cancelled > 0) {
ehci_trace_guest_bug(q->ehci, warn);
}
QTAILQ_REMOVE(head, q, next);
g_free(q);
}
Commit Message:
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: bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
if (!CrosLibrary::Get()->EnsureLoaded())
return false;
input_method_status_connection_ = chromeos::MonitorInputMethodStatus(
this,
&InputMethodChangedHandler,
&RegisterPropertiesHandler,
&UpdatePropertyHandler,
&ConnectionChangeHandler);
if (!input_method_status_connection_)
return false;
initialized_successfully_ = true;
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
Commit Message: Fix to prevent SASL security vulnerability
CWE ID: CWE-287
Target: 1
Example 2:
Code: int WebGraphicsContext3DCommandBufferImpl::GetChannelID() {
return host_ ? host_->client_id() : 0;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags,
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[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: static int jffs2_do_setattr (struct inode *inode, struct iattr *iattr)
{
struct jffs2_full_dnode *old_metadata, *new_metadata;
struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode);
struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb);
struct jffs2_raw_inode *ri;
union jffs2_device_node dev;
unsigned char *mdata = NULL;
int mdatalen = 0;
unsigned int ivalid;
uint32_t alloclen;
int ret;
D1(printk(KERN_DEBUG "jffs2_setattr(): ino #%lu\n", inode->i_ino));
ret = inode_change_ok(inode, iattr);
if (ret)
return ret;
/* Special cases - we don't want more than one data node
for these types on the medium at any time. So setattr
/* Special cases - we don't want more than one data node
for these types on the medium at any time. So setattr
must read the original data associated with the node
(i.e. the device numbers or the target name) and write
it out again with the appropriate data attached */
if (S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode)) {
/* For these, we don't actually need to read the old node */
mdatalen = jffs2_encode_dev(&dev, inode->i_rdev);
mdata = (char *)&dev;
D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of kdev_t\n", mdatalen));
} else if (S_ISLNK(inode->i_mode)) {
down(&f->sem);
mdatalen = f->metadata->size;
mdata = kmalloc(f->metadata->size, GFP_USER);
if (!mdata) {
up(&f->sem);
return -ENOMEM;
}
ret = jffs2_read_dnode(c, f, f->metadata, mdata, 0, mdatalen);
if (ret) {
up(&f->sem);
kfree(mdata);
return ret;
}
up(&f->sem);
D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of symlink target\n", mdatalen));
}
ri = jffs2_alloc_raw_inode();
if (!ri) {
if (S_ISLNK(inode->i_mode))
kfree(mdata);
return -ENOMEM;
}
ret = jffs2_reserve_space(c, sizeof(*ri) + mdatalen, &alloclen,
ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE);
if (ret) {
jffs2_free_raw_inode(ri);
if (S_ISLNK(inode->i_mode & S_IFMT))
kfree(mdata);
return ret;
}
down(&f->sem);
ivalid = iattr->ia_valid;
ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE);
ri->totlen = cpu_to_je32(sizeof(*ri) + mdatalen);
ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4));
ri->ino = cpu_to_je32(inode->i_ino);
ri->version = cpu_to_je32(++f->highest_version);
ri->uid = cpu_to_je16((ivalid & ATTR_UID)?iattr->ia_uid:inode->i_uid);
ri->gid = cpu_to_je16((ivalid & ATTR_GID)?iattr->ia_gid:inode->i_gid);
if (ivalid & ATTR_MODE)
if (iattr->ia_mode & S_ISGID &&
!in_group_p(je16_to_cpu(ri->gid)) && !capable(CAP_FSETID))
ri->mode = cpu_to_jemode(iattr->ia_mode & ~S_ISGID);
else
ri->mode = cpu_to_jemode(iattr->ia_mode);
else
ri->mode = cpu_to_jemode(inode->i_mode);
ri->isize = cpu_to_je32((ivalid & ATTR_SIZE)?iattr->ia_size:inode->i_size);
ri->atime = cpu_to_je32(I_SEC((ivalid & ATTR_ATIME)?iattr->ia_atime:inode->i_atime));
ri->mtime = cpu_to_je32(I_SEC((ivalid & ATTR_MTIME)?iattr->ia_mtime:inode->i_mtime));
ri->ctime = cpu_to_je32(I_SEC((ivalid & ATTR_CTIME)?iattr->ia_ctime:inode->i_ctime));
ri->offset = cpu_to_je32(0);
ri->csize = ri->dsize = cpu_to_je32(mdatalen);
ri->compr = JFFS2_COMPR_NONE;
if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) {
/* It's an extension. Make it a hole node */
ri->compr = JFFS2_COMPR_ZERO;
ri->dsize = cpu_to_je32(iattr->ia_size - inode->i_size);
ri->offset = cpu_to_je32(inode->i_size);
}
ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8));
if (mdatalen)
ri->data_crc = cpu_to_je32(crc32(0, mdata, mdatalen));
else
ri->data_crc = cpu_to_je32(0);
new_metadata = jffs2_write_dnode(c, f, ri, mdata, mdatalen, ALLOC_NORMAL);
if (S_ISLNK(inode->i_mode))
kfree(mdata);
if (IS_ERR(new_metadata)) {
jffs2_complete_reservation(c);
jffs2_free_raw_inode(ri);
up(&f->sem);
return PTR_ERR(new_metadata);
}
/* It worked. Update the inode */
inode->i_atime = ITIME(je32_to_cpu(ri->atime));
inode->i_ctime = ITIME(je32_to_cpu(ri->ctime));
inode->i_mtime = ITIME(je32_to_cpu(ri->mtime));
inode->i_mode = jemode_to_cpu(ri->mode);
inode->i_uid = je16_to_cpu(ri->uid);
inode->i_gid = je16_to_cpu(ri->gid);
old_metadata = f->metadata;
if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size)
jffs2_truncate_fragtree (c, &f->fragtree, iattr->ia_size);
if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) {
jffs2_add_full_dnode_to_inode(c, f, new_metadata);
inode->i_size = iattr->ia_size;
f->metadata = NULL;
} else {
f->metadata = new_metadata;
}
if (old_metadata) {
jffs2_mark_node_obsolete(c, old_metadata->raw);
jffs2_free_full_dnode(old_metadata);
}
jffs2_free_raw_inode(ri);
up(&f->sem);
jffs2_complete_reservation(c);
/* We have to do the vmtruncate() without f->sem held, since
some pages may be locked and waiting for it in readpage().
We are protected from a simultaneous write() extending i_size
back past iattr->ia_size, because do_truncate() holds the
generic inode semaphore. */
if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size)
vmtruncate(inode, iattr->ia_size);
return 0;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: struct kern_ipc_perm *ipc_lock(struct ipc_ids *ids, int id)
{
struct kern_ipc_perm *out;
rcu_read_lock();
out = ipc_obtain_object(ids, id);
if (IS_ERR(out))
goto err1;
spin_lock(&out->lock);
/* ipc_rmid() may have already freed the ID while ipc_lock
* was spinning: here verify that the structure is still valid
*/
if (!out->deleted)
return out;
spin_unlock(&out->lock);
out = ERR_PTR(-EINVAL);
err1:
rcu_read_unlock();
return out;
}
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: CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebsiteSettings::OnUIClosing() {
if (show_info_bar_)
WebsiteSettingsInfoBarDelegate::Create(infobar_service_);
SSLCertificateDecisionsDidRevoke user_decision =
did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED
: USER_CERT_DECISIONS_NOT_REVOKED;
UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions",
user_decision,
END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM);
}
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:
Target: 1
Example 2:
Code: DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: DownloadUrlParameters(url,
-1,
-1,
-1,
traffic_annotation) {}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
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 UsbOpenDeviceFunction::OnDeviceOpened(
scoped_refptr<UsbDeviceHandle> device_handle) {
if (!device_handle.get()) {
Respond(Error(kErrorOpen));
return;
}
RecordDeviceLastUsed();
ApiResourceManager<UsbDeviceResource>* manager =
ApiResourceManager<UsbDeviceResource>::Get(browser_context());
scoped_refptr<UsbDevice> device = device_handle->GetDevice();
Respond(OneArgument(PopulateConnectionHandle(
manager->Add(new UsbDeviceResource(extension_id(), device_handle)),
device->vendor_id(), device->product_id())));
}
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
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: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: void ExpectNoValidImageCallback(const base::Closure& quit_closure,
int id,
int status_code,
const GURL& image_url,
const std::vector<SkBitmap>& bitmap,
const std::vector<gfx::Size>& sizes) {
EXPECT_EQ(200, status_code);
EXPECT_TRUE(bitmap.empty());
EXPECT_TRUE(sizes.empty());
quit_closure.Run();
}
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: const extensions::Extension* GetExtension(Profile* profile,
const std::string& extension_id) {
const ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
const extensions::Extension* extension =
service->GetInstalledExtension(extension_id);
return extension;
}
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 RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
RenderStyle* oldStyle = style();
s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle.position()
&& containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
markAllDescendantsWithFloatsForLayout();
RenderBlock::styleWillChange(diff, newStyle);
}
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: 1
Example 2:
Code: static int proc_tty_ldiscs_open(struct inode *inode, struct file *file)
{
return seq_open(file, &tty_ldiscs_seq_ops);
}
Commit Message: tty: Prevent ldisc drivers from re-using stale tty fields
Line discipline drivers may mistakenly misuse ldisc-related fields
when initializing. For example, a failure to initialize tty->receive_room
in the N_GIGASET_M101 line discipline was recently found and fixed [1].
Now, the N_X25 line discipline has been discovered accessing the previous
line discipline's already-freed private data [2].
Harden the ldisc interface against misuse by initializing revelant
tty fields before instancing the new line discipline.
[1]
commit fd98e9419d8d622a4de91f76b306af6aa627aa9c
Author: Tilman Schmidt <[email protected]>
Date: Tue Jul 14 00:37:13 2015 +0200
isdn/gigaset: reset tty->receive_room when attaching ser_gigaset
[2] Report from Sasha Levin <[email protected]>
[ 634.336761] ==================================================================
[ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0
[ 634.339558] Read of size 4 by task syzkaller_execu/8981
[ 634.340359] =============================================================================
[ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected
...
[ 634.405018] Call Trace:
[ 634.405277] dump_stack (lib/dump_stack.c:52)
[ 634.405775] print_trailer (mm/slub.c:655)
[ 634.406361] object_err (mm/slub.c:662)
[ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236)
[ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279)
[ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1))
[ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447)
[ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567)
[ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879)
[ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607)
[ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613)
[ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188)
Cc: Tilman Schmidt <[email protected]>
Cc: Sasha Levin <[email protected]>
Signed-off-by: Peter Hurley <[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: TestFlashMessageLoop::~TestFlashMessageLoop() {
PP_DCHECK(!message_loop_);
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void NavigationControllerImpl::InsertOrReplaceEntry(
std::unique_ptr<NavigationEntryImpl> entry,
bool replace) {
DCHECK(!ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
ui::PAGE_TRANSITION_AUTO_SUBFRAME));
if (pending_entry_ && pending_entry_index_ == -1)
entry->set_unique_id(pending_entry_->GetUniqueID());
DiscardNonCommittedEntriesInternal();
int current_size = static_cast<int>(entries_.size());
if (replace && current_size > 0) {
CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
*entries_[last_committed_entry_index_], entry.get());
entries_[last_committed_entry_index_] = std::move(entry);
return;
}
DCHECK(!replace);
if (current_size > 0) {
int num_pruned = 0;
while (last_committed_entry_index_ < (current_size - 1)) {
num_pruned++;
entries_.pop_back();
current_size--;
}
if (num_pruned > 0) // Only notify if we did prune something.
NotifyPrunedEntries(this, false, num_pruned);
}
PruneOldestEntryIfFull();
entries_.push_back(std::move(entry));
last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
}
Commit Message: Preserve renderer-initiated bit when reloading in a new process.
BUG=847718
TEST=See bug for repro steps.
Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227
Reviewed-on: https://chromium-review.googlesource.com/1080235
Commit-Queue: Charlie Reis <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563312}
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 HTMLMediaElement::SelectInitialTracksIfNecessary() {
if (!MediaTracksEnabledInternally())
return;
if (audioTracks().length() > 0 && !audioTracks().HasEnabledTrack())
audioTracks().AnonymousIndexedGetter(0)->setEnabled(true);
if (videoTracks().length() > 0 && videoTracks().selectedIndex() == -1)
videoTracks().AnonymousIndexedGetter(0)->setSelected(true);
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
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 treeRead(struct READER *reader, struct DATAOBJECT *data) {
int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,
szy;
char *input, *output;
uint8_t node_type, node_level;
uint16_t entries_used;
uint32_t size_of_chunk;
uint32_t filter_mask;
uint64_t address_of_left_sibling, address_of_right_sibling, start[4],
child_pointer, key, store;
char buf[4];
UNUSED(node_level);
UNUSED(address_of_right_sibling);
UNUSED(address_of_left_sibling);
UNUSED(key);
if (data->ds.dimensionality > 3) {
log("TREE dimensions > 3");
return MYSOFA_INVALID_FORMAT;
}
/* read signature */
if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) {
log("cannot read signature of TREE\n");
return MYSOFA_INVALID_FORMAT;
} log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf);
node_type = (uint8_t)fgetc(reader->fhd);
node_level = (uint8_t)fgetc(reader->fhd);
entries_used = (uint16_t)readValue(reader, 2);
if(entries_used>0x1000)
return MYSOFA_UNSUPPORTED_FORMAT;
address_of_left_sibling = readValue(reader,
reader->superblock.size_of_offsets);
address_of_right_sibling = readValue(reader,
reader->superblock.size_of_offsets);
elements = 1;
for (j = 0; j < data->ds.dimensionality; j++)
elements *= data->datalayout_chunk[j];
dy = data->datalayout_chunk[1];
dz = data->datalayout_chunk[2];
sx = data->ds.dimension_size[0];
sy = data->ds.dimension_size[1];
sz = data->ds.dimension_size[2];
dzy = dz * dy;
szy = sz * sy;
size = data->datalayout_chunk[data->ds.dimensionality];
log("elements %d size %d\n",elements,size);
if (!(output = malloc(elements * size))) {
return MYSOFA_NO_MEMORY;
}
for (e = 0; e < entries_used * 2; e++) {
if (node_type == 0) {
key = readValue(reader, reader->superblock.size_of_lengths);
} else {
size_of_chunk = (uint32_t)readValue(reader, 4);
filter_mask = (uint32_t)readValue(reader, 4);
if (filter_mask) {
log("TREE all filters must be enabled\n");
free(output);
return MYSOFA_INVALID_FORMAT;
}
for (j = 0; j < data->ds.dimensionality; j++) {
start[j] = readValue(reader, 8);
log("start %d %lu\n",j,start[j]);
}
if (readValue(reader, 8)) {
break;
}
child_pointer = readValue(reader,
reader->superblock.size_of_offsets);
log(" data at %lX len %u\n", child_pointer, size_of_chunk);
/* read data */
store = ftell(reader->fhd);
if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {
free(output);
return errno;
}
if (!(input = malloc(size_of_chunk))) {
free(output);
return MYSOFA_NO_MEMORY;
}
if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {
free(output);
free(input);
return MYSOFA_INVALID_FORMAT;
}
olen = elements * size;
err = gunzip(size_of_chunk, input, &olen, output);
free(input);
log(" gunzip %d %d %d\n",err, olen, elements*size);
if (err || olen != elements * size) {
free(output);
return MYSOFA_INVALID_FORMAT;
}
switch (data->ds.dimensionality) {
case 1:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements + start[0];
if (x < sx) {
j = x * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 2:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
y = x % dy + start[1];
x = x / dy + start[0];
if (y < sy && x < sx) {
j = ((x * sy + y) * size) + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 3:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
z = x % dz + start[2];
y = (x / dz) % dy + start[1];
x = (x / dzy) + start[0];
if (z < sz && y < sy && x < sx) {
j = (x * szy + y * sz + z) * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
default:
log("invalid dim\n");
return MYSOFA_INTERNAL_ERROR;
}
if(fseek(reader->fhd, store, SEEK_SET)<0) {
free(output);
return errno;
}
}
}
free(output);
if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */
return errno;
return MYSOFA_OK;
}
Commit Message: Fixed security issue 1
CWE ID: CWE-20
Target: 1
Example 2:
Code: static WORD32 ihevcd_parse_hrd_parameters(bitstrm_t *ps_bitstrm,
hrd_params_t *ps_hrd,
WORD32 common_info_present_flag,
WORD32 max_num_sub_layers_minus1)
{
WORD32 ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 i;
ps_hrd->u1_nal_hrd_parameters_present_flag = 0;
ps_hrd->u1_vcl_hrd_parameters_present_flag = 0;
ps_hrd->u1_sub_pic_cpb_params_present_flag = 0;
ps_hrd->u1_tick_divisor_minus2 = 0;
ps_hrd->u1_du_cpb_removal_delay_increment_length_minus1 = 0;
ps_hrd->u1_sub_pic_cpb_params_in_pic_timing_sei_flag = 0;
ps_hrd->u1_dpb_output_delay_du_length_minus1 = 0;
ps_hrd->u4_bit_rate_scale = 0;
ps_hrd->u4_cpb_size_scale = 0;
ps_hrd->u4_cpb_size_du_scale = 0;
ps_hrd->u1_initial_cpb_removal_delay_length_minus1 = 23;
ps_hrd->u1_au_cpb_removal_delay_length_minus1 = 23;
ps_hrd->u1_dpb_output_delay_length_minus1 = 23;
if(common_info_present_flag)
{
BITS_PARSE("nal_hrd_parameters_present_flag", ps_hrd->u1_nal_hrd_parameters_present_flag, ps_bitstrm, 1);
BITS_PARSE("vcl_hrd_parameters_present_flag", ps_hrd->u1_vcl_hrd_parameters_present_flag, ps_bitstrm, 1);
if(ps_hrd->u1_nal_hrd_parameters_present_flag || ps_hrd->u1_vcl_hrd_parameters_present_flag)
{
BITS_PARSE("sub_pic_cpb_params_present_flag", ps_hrd->u1_sub_pic_cpb_params_present_flag, ps_bitstrm, 1);
if(ps_hrd->u1_sub_pic_cpb_params_present_flag)
{
BITS_PARSE("tick_divisor_minus2", ps_hrd->u1_tick_divisor_minus2, ps_bitstrm, 8);
BITS_PARSE("du_cpb_removal_delay_increment_length_minus1", ps_hrd->u1_du_cpb_removal_delay_increment_length_minus1, ps_bitstrm, 5);
BITS_PARSE("sub_pic_cpb_params_in_pic_timing_sei_flag", ps_hrd->u1_sub_pic_cpb_params_in_pic_timing_sei_flag, ps_bitstrm, 1);
BITS_PARSE("dpb_output_delay_du_length_minus1", ps_hrd->u1_dpb_output_delay_du_length_minus1, ps_bitstrm, 5);
}
BITS_PARSE("bit_rate_scale", ps_hrd->u4_bit_rate_scale, ps_bitstrm, 4);
BITS_PARSE("cpb_size_scale", ps_hrd->u4_cpb_size_scale, ps_bitstrm, 4);
if(ps_hrd->u1_sub_pic_cpb_params_present_flag)
BITS_PARSE("cpb_size_du_scale", ps_hrd->u4_cpb_size_du_scale, ps_bitstrm, 4);
BITS_PARSE("initial_cpb_removal_delay_length_minus1", ps_hrd->u1_initial_cpb_removal_delay_length_minus1, ps_bitstrm, 5);
BITS_PARSE("au_cpb_removal_delay_length_minus1", ps_hrd->u1_au_cpb_removal_delay_length_minus1, ps_bitstrm, 5);
BITS_PARSE("dpb_output_delay_length_minus1", ps_hrd->u1_dpb_output_delay_length_minus1, ps_bitstrm, 5);
}
}
for(i = 0; i <= max_num_sub_layers_minus1; i++)
{
BITS_PARSE("fixed_pic_rate_general_flag[ i ]", ps_hrd->au1_fixed_pic_rate_general_flag[i], ps_bitstrm, 1);
ps_hrd->au1_fixed_pic_rate_within_cvs_flag[i] = 1;
ps_hrd->au1_elemental_duration_in_tc_minus1[i] = 0;
ps_hrd->au1_low_delay_hrd_flag[i] = 0;
ps_hrd->au1_cpb_cnt_minus1[i] = 0;
if(!ps_hrd->au1_fixed_pic_rate_general_flag[i])
BITS_PARSE("fixed_pic_rate_within_cvs_flag[ i ]", ps_hrd->au1_fixed_pic_rate_within_cvs_flag[i], ps_bitstrm, 1);
if(ps_hrd->au1_fixed_pic_rate_within_cvs_flag[i])
{
UEV_PARSE("elemental_duration_in_tc_minus1[ i ]", ps_hrd->au1_elemental_duration_in_tc_minus1[i], ps_bitstrm);
}
else
{
BITS_PARSE("low_delay_hrd_flag[ i ]", ps_hrd->au1_low_delay_hrd_flag[i], ps_bitstrm, 1);
}
if(!ps_hrd->au1_low_delay_hrd_flag[i])
UEV_PARSE("cpb_cnt_minus1[ i ]", ps_hrd->au1_cpb_cnt_minus1[i], ps_bitstrm);
if(ps_hrd->u1_nal_hrd_parameters_present_flag)
ihevcd_parse_sub_layer_hrd_parameters(ps_bitstrm,
&ps_hrd->as_sub_layer_hrd_params[i],
ps_hrd->au1_cpb_cnt_minus1[i],
ps_hrd->u1_sub_pic_cpb_params_present_flag);
if(ps_hrd->u1_vcl_hrd_parameters_present_flag)
ihevcd_parse_sub_layer_hrd_parameters(ps_bitstrm,
&ps_hrd->as_sub_layer_hrd_params[i],
ps_hrd->au1_cpb_cnt_minus1[i],
ps_hrd->u1_sub_pic_cpb_params_present_flag);
}
return ret;
}
Commit Message: Correct Tiles rows and cols check
Bug: 36231493
Bug: 34064500
Change-Id: Ib17b2c68360685c5a2c019e1497612a130f9f76a
(cherry picked from commit 07ef4e7138e0e13d61039530358343a19308b188)
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 ZIPARCHIVE_METHOD(setArchiveComment)
{
struct zip *intern;
zval *this = getThis();
int comment_len;
char * comment;
if (!this) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, this);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &comment, &comment_len) == FAILURE) {
return;
}
if (zip_set_archive_comment(intern, (const char *)comment, (int)comment_len)) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize
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: key_ref_t key_create_or_update(key_ref_t keyring_ref,
const char *type,
const char *description,
const void *payload,
size_t plen,
key_perm_t perm,
unsigned long flags)
{
struct keyring_index_key index_key = {
.description = description,
};
struct key_preparsed_payload prep;
struct assoc_array_edit *edit;
const struct cred *cred = current_cred();
struct key *keyring, *key = NULL;
key_ref_t key_ref;
int ret;
/* look up the key type to see if it's one of the registered kernel
* types */
index_key.type = key_type_lookup(type);
if (IS_ERR(index_key.type)) {
key_ref = ERR_PTR(-ENODEV);
goto error;
}
key_ref = ERR_PTR(-EINVAL);
if (!index_key.type->match || !index_key.type->instantiate ||
(!index_key.description && !index_key.type->preparse))
goto error_put_type;
keyring = key_ref_to_ptr(keyring_ref);
key_check(keyring);
key_ref = ERR_PTR(-ENOTDIR);
if (keyring->type != &key_type_keyring)
goto error_put_type;
memset(&prep, 0, sizeof(prep));
prep.data = payload;
prep.datalen = plen;
prep.quotalen = index_key.type->def_datalen;
prep.trusted = flags & KEY_ALLOC_TRUSTED;
prep.expiry = TIME_T_MAX;
if (index_key.type->preparse) {
ret = index_key.type->preparse(&prep);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_free_prep;
}
if (!index_key.description)
index_key.description = prep.description;
key_ref = ERR_PTR(-EINVAL);
if (!index_key.description)
goto error_free_prep;
}
index_key.desc_len = strlen(index_key.description);
key_ref = ERR_PTR(-EPERM);
if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags))
goto error_free_prep;
flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0;
ret = __key_link_begin(keyring, &index_key, &edit);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_free_prep;
}
/* if we're going to allocate a new key, we're going to have
* to modify the keyring */
ret = key_permission(keyring_ref, KEY_NEED_WRITE);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_link_end;
}
/* if it's possible to update this type of key, search for an existing
* key of the same type and description in the destination keyring and
* update that instead if possible
*/
if (index_key.type->update) {
key_ref = find_key_to_update(keyring_ref, &index_key);
if (key_ref)
goto found_matching_key;
}
/* if the client doesn't provide, decide on the permissions we want */
if (perm == KEY_PERM_UNDEF) {
perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
perm |= KEY_USR_VIEW;
if (index_key.type->read)
perm |= KEY_POS_READ;
if (index_key.type == &key_type_keyring ||
index_key.type->update)
perm |= KEY_POS_WRITE;
}
/* allocate a new key */
key = key_alloc(index_key.type, index_key.description,
cred->fsuid, cred->fsgid, cred, perm, flags);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error_link_end;
}
/* instantiate it and link it into the target keyring */
ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
if (ret < 0) {
key_put(key);
key_ref = ERR_PTR(ret);
goto error_link_end;
}
key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
error_link_end:
__key_link_end(keyring, &index_key, edit);
error_free_prep:
if (index_key.type->preparse)
index_key.type->free_preparse(&prep);
error_put_type:
key_type_put(index_key.type);
error:
return key_ref;
found_matching_key:
/* we found a matching key, so we're going to try to update it
* - we can drop the locks first as we have the key pinned
*/
__key_link_end(keyring, &index_key, edit);
key_ref = __key_update(key_ref, &prep);
goto error_free_prep;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: config_auth(
config_tree *ptree
)
{
attr_val * my_val;
int first;
int last;
int i;
#ifdef AUTOKEY
int item;
#endif
/* Crypto Command */
#ifdef AUTOKEY
item = -1; /* quiet warning */
my_val = HEAD_PFIFO(ptree->auth.crypto_cmd_list);
for (; my_val != NULL; my_val = my_val->link) {
switch (my_val->attr) {
default:
NTP_INSIST(0);
break;
case T_Host:
item = CRYPTO_CONF_PRIV;
break;
case T_Ident:
item = CRYPTO_CONF_IDENT;
break;
case T_Pw:
item = CRYPTO_CONF_PW;
break;
case T_Randfile:
item = CRYPTO_CONF_RAND;
break;
case T_Digest:
item = CRYPTO_CONF_NID;
break;
}
crypto_config(item, my_val->value.s);
}
#endif /* AUTOKEY */
/* Keysdir Command */
if (ptree->auth.keysdir) {
if (keysdir != default_keysdir)
free(keysdir);
keysdir = estrdup(ptree->auth.keysdir);
}
/* ntp_signd_socket Command */
if (ptree->auth.ntp_signd_socket) {
if (ntp_signd_socket != default_ntp_signd_socket)
free(ntp_signd_socket);
ntp_signd_socket = estrdup(ptree->auth.ntp_signd_socket);
}
#ifdef AUTOKEY
if (ptree->auth.cryptosw && !cryptosw) {
crypto_setup();
cryptosw = 1;
}
#endif /* AUTOKEY */
/* Keys Command */
if (ptree->auth.keys)
getauthkeys(ptree->auth.keys);
/* Control Key Command */
if (ptree->auth.control_key)
ctl_auth_keyid = (keyid_t)ptree->auth.control_key;
/* Requested Key Command */
if (ptree->auth.request_key) {
DPRINTF(4, ("set info_auth_keyid to %08lx\n",
(u_long) ptree->auth.request_key));
info_auth_keyid = (keyid_t)ptree->auth.request_key;
}
/* Trusted Key Command */
my_val = HEAD_PFIFO(ptree->auth.trusted_key_list);
for (; my_val != NULL; my_val = my_val->link) {
if (T_Integer == my_val->type)
authtrust(my_val->value.i, 1);
else if (T_Intrange == my_val->type) {
first = my_val->value.r.first;
last = my_val->value.r.last;
if (first > last || first < 1 || last > 65534)
msyslog(LOG_NOTICE,
"Ignoring invalid trustedkey range %d ... %d, min 1 max 65534.",
first, last);
else
for (i = first; i <= last; i++)
authtrust((keyid_t)i, 1);
}
}
#ifdef AUTOKEY
/* crypto revoke command */
if (ptree->auth.revoke)
sys_revoke = 1 << ptree->auth.revoke;
#endif /* AUTOKEY */
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
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 send_reply_chunks(struct svcxprt_rdma *xprt,
struct rpcrdma_write_array *rp_ary,
struct rpcrdma_msg *rdma_resp,
struct svc_rqst *rqstp,
struct svc_rdma_req_map *vec)
{
u32 xfer_len = rqstp->rq_res.len;
int write_len;
u32 xdr_off;
int chunk_no;
int chunk_off;
int nchunks;
struct rpcrdma_segment *ch;
struct rpcrdma_write_array *res_ary;
int ret;
/* XXX: need to fix when reply lists occur with read-list and or
* write-list */
res_ary = (struct rpcrdma_write_array *)
&rdma_resp->rm_body.rm_chunks[2];
/* xdr offset starts at RPC message */
nchunks = be32_to_cpu(rp_ary->wc_nchunks);
for (xdr_off = 0, chunk_no = 0;
xfer_len && chunk_no < nchunks;
chunk_no++) {
u64 rs_offset;
ch = &rp_ary->wc_array[chunk_no].wc_target;
write_len = min(xfer_len, be32_to_cpu(ch->rs_length));
/* Prepare the reply chunk given the length actually
* written */
xdr_decode_hyper((__be32 *)&ch->rs_offset, &rs_offset);
svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no,
ch->rs_handle, ch->rs_offset,
write_len);
chunk_off = 0;
while (write_len) {
ret = send_write(xprt, rqstp,
be32_to_cpu(ch->rs_handle),
rs_offset + chunk_off,
xdr_off,
write_len,
vec);
if (ret <= 0)
goto out_err;
chunk_off += ret;
xdr_off += ret;
xfer_len -= ret;
write_len -= ret;
}
}
/* Update the req with the number of chunks actually used */
svc_rdma_xdr_encode_reply_array(res_ary, chunk_no);
return rqstp->rq_res.len;
out_err:
pr_err("svcrdma: failed to send reply chunks, rc=%d\n", ret);
return -EIO;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PP_Resource ResourceTracker::AddResource(Resource* resource) {
if (last_resource_id_ ==
(std::numeric_limits<PP_Resource>::max() >> kPPIdTypeBits))
return 0;
PP_Resource new_id = MakeTypedId(++last_resource_id_, PP_ID_TYPE_RESOURCE);
live_resources_.insert(std::make_pair(new_id, std::make_pair(resource, 1)));
PP_Instance pp_instance = resource->instance()->pp_instance();
DCHECK(instance_map_.find(pp_instance) != instance_map_.end());
instance_map_[pp_instance]->resources.insert(new_id);
return new_id;
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MagickPathExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MagickPathExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MagickPathExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MagickPathExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MagickPathExtent-1);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MagickPathExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickString(image2->filename,image->filename,MagickPathExtent);
(void) CopyMagickString(image2->magick_filename,image->magick_filename,MagickPathExtent);
(void) CopyMagickString(image2->magick,image->magick,MagickPathExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/85
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: isatap_chksrc(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *t)
{
struct ip_tunnel_prl_entry *p;
int ok = 1;
rcu_read_lock();
p = __ipip6_tunnel_locate_prl(t, iph->saddr);
if (p) {
if (p->flags & PRL_DEFAULT)
skb->ndisc_nodetype = NDISC_NODETYPE_DEFAULT;
else
skb->ndisc_nodetype = NDISC_NODETYPE_NODEFAULT;
} else {
const struct in6_addr *addr6 = &ipv6_hdr(skb)->saddr;
if (ipv6_addr_is_isatap(addr6) &&
(addr6->s6_addr32[3] == iph->saddr) &&
ipv6_chk_prefix(addr6, t->dev))
skb->ndisc_nodetype = NDISC_NODETYPE_HOST;
else
ok = 0;
}
rcu_read_unlock();
return ok;
}
Commit Message: net: sit: fix memory leak in sit_init_net()
If register_netdev() is failed to register sitn->fb_tunnel_dev,
it will go to err_reg_dev and forget to free netdev(sitn->fb_tunnel_dev).
BUG: memory leak
unreferenced object 0xffff888378daad00 (size 512):
comm "syz-executor.1", pid 4006, jiffies 4295121142 (age 16.115s)
hex dump (first 32 bytes):
00 e6 ed c0 83 88 ff ff 00 00 00 00 00 00 00 00 ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
backtrace:
[<00000000d6dcb63e>] kvmalloc include/linux/mm.h:577 [inline]
[<00000000d6dcb63e>] kvzalloc include/linux/mm.h:585 [inline]
[<00000000d6dcb63e>] netif_alloc_netdev_queues net/core/dev.c:8380 [inline]
[<00000000d6dcb63e>] alloc_netdev_mqs+0x600/0xcc0 net/core/dev.c:8970
[<00000000867e172f>] sit_init_net+0x295/0xa40 net/ipv6/sit.c:1848
[<00000000871019fa>] ops_init+0xad/0x3e0 net/core/net_namespace.c:129
[<00000000319507f6>] setup_net+0x2ba/0x690 net/core/net_namespace.c:314
[<0000000087db4f96>] copy_net_ns+0x1dc/0x330 net/core/net_namespace.c:437
[<0000000057efc651>] create_new_namespaces+0x382/0x730 kernel/nsproxy.c:107
[<00000000676f83de>] copy_namespaces+0x2ed/0x3d0 kernel/nsproxy.c:165
[<0000000030b74bac>] copy_process.part.27+0x231e/0x6db0 kernel/fork.c:1919
[<00000000fff78746>] copy_process kernel/fork.c:1713 [inline]
[<00000000fff78746>] _do_fork+0x1bc/0xe90 kernel/fork.c:2224
[<000000001c2e0d1c>] do_syscall_64+0xc8/0x580 arch/x86/entry/common.c:290
[<00000000ec48bd44>] entry_SYSCALL_64_after_hwframe+0x49/0xbe
[<0000000039acff8a>] 0xffffffffffffffff
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-772
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 PopupContainer::showInRect(const IntRect& r, FrameView* v, int index)
{
listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0));
listBox()->updateFromElement();
IntPoint location = v->contentsToWindow(r.location());
location.move(0, r.height());
m_originalFrameRect = IntRect(location, r.size());
setFrameRect(m_originalFrameRect);
showPopup(v);
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void __invept(int ext, u64 eptp, gpa_t gpa)
{
struct {
u64 eptp, gpa;
} operand = {eptp, gpa};
asm volatile (__ex(ASM_VMX_INVEPT)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:\n"
: : "a" (&operand), "c" (ext) : "cc", "memory");
}
Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry
CR4 isn't constant; at least the TSD and PCE bits can vary.
TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks
like it's correct.
This adds a branch and a read from cr4 to each vm entry. Because it is
extremely likely that consecutive entries into the same vcpu will have
the same host cr4 value, this fixes up the vmcs instead of restoring cr4
after the fact. A subsequent patch will add a kernel-wide cr4 shadow,
reducing the overhead in the common case to just two memory reads and a
branch.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: Paolo Bonzini <[email protected]>
Cc: [email protected]
Cc: Petr Matousek <[email protected]>
Cc: Gleb Natapov <[email protected]>
Signed-off-by: Linus Torvalds <[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: IPV6DefragSturgesNovakLinuxTest(void)
{
/* Expected data. */
u_char expected[] = {
"AAAAAAAA"
"AAAAAAAA"
"AAAAAAAA"
"JJJJJJJJ"
"JJJJJJJJ"
"BBBBBBBB"
"KKKKKKKK"
"KKKKKKKK"
"KKKKKKKK"
"LLLLLLLL"
"LLLLLLLL"
"LLLLLLLL"
"MMMMMMMM"
"MMMMMMMM"
"MMMMMMMM"
"FFFFFFFF"
"FFFFFFFF"
"FFFFFFFF"
"GGGGGGGG"
"GGGGGGGG"
"PPPPPPPP"
"HHHHHHHH"
"QQQQQQQQ"
"QQQQQQQQ"
};
return IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_LINUX, expected,
sizeof(expected));
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
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: WebTransformationMatrix WebTransformOperations::blend(const WebTransformOperations& from, double progress) const
{
WebTransformationMatrix toReturn;
bool fromIdentity = from.isIdentity();
bool toIdentity = isIdentity();
if (fromIdentity && toIdentity)
return toReturn;
if (matchesTypes(from)) {
size_t numOperations = max(fromIdentity ? 0 : from.m_private->operations.size(),
toIdentity ? 0 : m_private->operations.size());
for (size_t i = 0; i < numOperations; ++i) {
WebTransformationMatrix blended = blendTransformOperations(
fromIdentity ? 0 : &from.m_private->operations[i],
toIdentity ? 0 : &m_private->operations[i],
progress);
toReturn.multiply(blended);
}
} else {
toReturn = apply();
WebTransformationMatrix fromTransform = from.apply();
toReturn.blend(fromTransform, progress);
}
return toReturn;
}
Commit Message: [chromium] We should accelerate all transformations, except when we must blend matrices that cannot be decomposed.
https://bugs.webkit.org/show_bug.cgi?id=95855
Reviewed by James Robinson.
Source/Platform:
WebTransformOperations are now able to report if they can successfully blend.
WebTransformationMatrix::blend now returns a bool if blending would fail.
* chromium/public/WebTransformOperations.h:
(WebTransformOperations):
* chromium/public/WebTransformationMatrix.h:
(WebTransformationMatrix):
Source/WebCore:
WebTransformOperations are now able to report if they can successfully blend.
WebTransformationMatrix::blend now returns a bool if blending would fail.
Unit tests:
AnimationTranslationUtilTest.createTransformAnimationWithNonDecomposableMatrix
AnimationTranslationUtilTest.createTransformAnimationWithNonInvertibleTransform
* platform/chromium/support/WebTransformOperations.cpp:
(WebKit::blendTransformOperations):
(WebKit::WebTransformOperations::blend):
(WebKit::WebTransformOperations::canBlendWith):
(WebKit):
(WebKit::WebTransformOperations::blendInternal):
* platform/chromium/support/WebTransformationMatrix.cpp:
(WebKit::WebTransformationMatrix::blend):
* platform/graphics/chromium/AnimationTranslationUtil.cpp:
(WebCore::WebTransformAnimationCurve):
Source/WebKit/chromium:
Added the following unit tests:
AnimationTranslationUtilTest.createTransformAnimationWithNonDecomposableMatrix
AnimationTranslationUtilTest.createTransformAnimationWithNonInvertibleTransform
* tests/AnimationTranslationUtilTest.cpp:
(WebKit::TEST):
(WebKit):
git-svn-id: svn://svn.chromium.org/blink/trunk@127868 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline double DrawEpsilonReciprocal(const double x)
{
#define DrawEpsilon (1.0e-6)
double sign = x < 0.0 ? -1.0 : 1.0;
return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));
}
Commit Message: Prevent buffer overflow in magick/draw.c
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dn_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
switch (sock->type) {
case SOCK_SEQPACKET:
if (protocol != DNPROTO_NSP)
return -EPROTONOSUPPORT;
break;
case SOCK_STREAM:
break;
default:
return -ESOCKTNOSUPPORT;
}
if ((sk = dn_alloc_sock(net, sock, GFP_KERNEL, kern)) == NULL)
return -ENOBUFS;
sk->sk_protocol = protocol;
return 0;
}
Commit Message: net: add validation for the socket syscall protocol argument
郭永刚 reported that one could simply crash the kernel as root by
using a simple program:
int socket_fd;
struct sockaddr_in addr;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = 10;
socket_fd = socket(10,3,0x40000000);
connect(socket_fd , &addr,16);
AF_INET, AF_INET6 sockets actually only support 8-bit protocol
identifiers. inet_sock's skc_protocol field thus is sized accordingly,
thus larger protocol identifiers simply cut off the higher bits and
store a zero in the protocol fields.
This could lead to e.g. NULL function pointer because as a result of
the cut off inet_num is zero and we call down to inet_autobind, which
is NULL for raw sockets.
kernel: Call Trace:
kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70
kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80
kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110
kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80
kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200
kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10
kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89
I found no particular commit which introduced this problem.
CVE: CVE-2015-8543
Cc: Cong Wang <[email protected]>
Reported-by: 郭永刚 <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[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: send_results(struct iperf_test *test)
{
int r = 0;
cJSON *j;
cJSON *j_streams;
struct iperf_stream *sp;
cJSON *j_stream;
int sender_has_retransmits;
iperf_size_t bytes_transferred;
int retransmits;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddFloatToObject(j, "cpu_util_total", test->cpu_util[0]);
cJSON_AddFloatToObject(j, "cpu_util_user", test->cpu_util[1]);
cJSON_AddFloatToObject(j, "cpu_util_system", test->cpu_util[2]);
if ( ! test->sender )
sender_has_retransmits = -1;
else
sender_has_retransmits = test->sender_has_retransmits;
cJSON_AddIntToObject(j, "sender_has_retransmits", sender_has_retransmits);
/* If on the server and sending server output, then do this */
if (test->role == 's' && test->get_server_output) {
if (test->json_output) {
/* Add JSON output */
cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top);
}
else {
/* Add textual output */
size_t buflen = 0;
/* Figure out how much room we need to hold the complete output string */
struct iperf_textline *t;
TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
buflen += strlen(t->line);
}
/* Allocate and build it up from the component lines */
char *output = calloc(buflen + 1, 1);
TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
strncat(output, t->line, buflen);
buflen -= strlen(t->line);
}
cJSON_AddStringToObject(j, "server_output_text", output);
}
}
j_streams = cJSON_CreateArray();
if (j_streams == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddItemToObject(j, "streams", j_streams);
SLIST_FOREACH(sp, &test->streams, streams) {
j_stream = cJSON_CreateObject();
if (j_stream == NULL) {
i_errno = IEPACKAGERESULTS;
r = -1;
} else {
cJSON_AddItemToArray(j_streams, j_stream);
bytes_transferred = test->sender ? sp->result->bytes_sent : sp->result->bytes_received;
retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1;
cJSON_AddIntToObject(j_stream, "id", sp->id);
cJSON_AddIntToObject(j_stream, "bytes", bytes_transferred);
cJSON_AddIntToObject(j_stream, "retransmits", retransmits);
cJSON_AddFloatToObject(j_stream, "jitter", sp->jitter);
cJSON_AddIntToObject(j_stream, "errors", sp->cnt_error);
cJSON_AddIntToObject(j_stream, "packets", sp->packet_count);
}
}
if (r == 0 && test->debug) {
printf("send_results\n%s\n", cJSON_Print(j));
}
if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDRESULTS;
r = -1;
}
}
cJSON_Delete(j);
}
return r;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline bool TransformUsesBoxSize(const ComputedStyle& style) {
if ((style.TransformOriginX().IsPercent() ||
style.TransformOriginY().IsPercent()) &&
style.RequireTransformOrigin(ComputedStyle::kIncludeTransformOrigin,
ComputedStyle::kExcludeMotionPath))
return true;
if (style.Transform().DependsOnBoxSize())
return true;
if (style.Translate() && style.Translate()->DependsOnBoxSize())
return true;
if (style.HasOffset())
return true;
return false;
}
Commit Message: Fix SVG crash for v0 distribution into foreignObject.
We require a parent element to be an SVG element for non-svg-root
elements in order to create a LayoutObject for them. However, we checked
the light tree parent element, not the flat tree one which is the parent
for the layout tree construction. Note that this is just an issue in
Shadow DOM v0 since v1 does not allow shadow roots on SVG elements.
Bug: 915469
Change-Id: Id81843abad08814fae747b5bc81c09666583f130
Reviewed-on: https://chromium-review.googlesource.com/c/1382494
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#617487}
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: bool DownloadItemImpl::AllDataSaved() const { return all_data_saved_; }
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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: magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
file_regex_t rx;
if (ms->search.s == NULL)
return 0;
l = 0;
rc = file_regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
} else {
regmatch_t pmatch[1];
#ifndef REG_STARTEND
#define REG_STARTEND 0
size_t l = ms->search.s_len - 1;
char c = ms->search.s[l];
((char *)(intptr_t)ms->search.s)[l] = '\0';
#else
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = ms->search.s_len;
#endif
rc = file_regexec(&rx, (const char *)ms->search.s,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
((char *)(intptr_t)ms->search.s)[l] = c;
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
break;
}
}
file_regfree(&rx);
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
Commit Message: If requested, limit search length.
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void bt_clear_tag(struct blk_mq_bitmap_tags *bt, unsigned int tag)
{
const int index = TAG_TO_INDEX(bt, tag);
struct bt_wait_state *bs;
int wait_cnt;
clear_bit(TAG_TO_BIT(bt, tag), &bt->map[index].word);
/* Ensure that the wait list checks occur after clear_bit(). */
smp_mb();
bs = bt_wake_ptr(bt);
if (!bs)
return;
wait_cnt = atomic_dec_return(&bs->wait_cnt);
if (unlikely(wait_cnt < 0))
wait_cnt = atomic_inc_return(&bs->wait_cnt);
if (wait_cnt == 0) {
atomic_add(bt->wake_cnt, &bs->wait_cnt);
bt_index_atomic_inc(&bt->wake_index);
wake_up(&bs->wait);
}
}
Commit Message: blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void Ins_SANGW( INS_ARG )
{ (void)exc; (void)args;
/* instruction not supported anymore */
}
Commit Message:
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 RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
params->scale_factor = settings.scale_factor();
params->rasterize_pdf = settings.rasterize_pdf();
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->display_header_footer = settings.display_header_footer();
params->title = settings.title();
params->url = settings.url();
params->printed_doc_type = SkiaDocumentType::PDF;
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254
Target: 1
Example 2:
Code: tt_cmap13_char_index( TT_CMap cmap,
FT_UInt32 char_code )
{
return tt_cmap13_char_map_binary( cmap, &char_code, 0 );
}
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: static rx_handler_result_t macvlan_handle_frame(struct sk_buff **pskb)
{
struct macvlan_port *port;
struct sk_buff *skb = *pskb;
const struct ethhdr *eth = eth_hdr(skb);
const struct macvlan_dev *vlan;
const struct macvlan_dev *src;
struct net_device *dev;
unsigned int len = 0;
int ret = NET_RX_DROP;
port = macvlan_port_get_rcu(skb->dev);
if (is_multicast_ether_addr(eth->h_dest)) {
src = macvlan_hash_lookup(port, eth->h_source);
if (!src)
/* frame comes from an external address */
macvlan_broadcast(skb, port, NULL,
MACVLAN_MODE_PRIVATE |
MACVLAN_MODE_VEPA |
MACVLAN_MODE_PASSTHRU|
MACVLAN_MODE_BRIDGE);
else if (src->mode == MACVLAN_MODE_VEPA)
/* flood to everyone except source */
macvlan_broadcast(skb, port, src->dev,
MACVLAN_MODE_VEPA |
MACVLAN_MODE_BRIDGE);
else if (src->mode == MACVLAN_MODE_BRIDGE)
/*
* flood only to VEPA ports, bridge ports
* already saw the frame on the way out.
*/
macvlan_broadcast(skb, port, src->dev,
MACVLAN_MODE_VEPA);
return RX_HANDLER_PASS;
}
if (port->passthru)
vlan = list_first_entry(&port->vlans, struct macvlan_dev, list);
else
vlan = macvlan_hash_lookup(port, eth->h_dest);
if (vlan == NULL)
return RX_HANDLER_PASS;
dev = vlan->dev;
if (unlikely(!(dev->flags & IFF_UP))) {
kfree_skb(skb);
return RX_HANDLER_CONSUMED;
}
len = skb->len + ETH_HLEN;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
skb->dev = dev;
skb->pkt_type = PACKET_HOST;
ret = vlan->receive(skb);
out:
macvlan_count_rx(vlan, len, ret == NET_RX_SUCCESS, 0);
return RX_HANDLER_CONSUMED;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[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: void PrintWebViewHelper::OnPrintForPrintPreview(
const DictionaryValue& job_settings) {
DCHECK(is_preview_);
if (print_web_view_)
return;
if (!render_view()->webview())
return;
WebFrame* main_frame = render_view()->webview()->mainFrame();
if (!main_frame)
return;
WebDocument document = main_frame->document();
WebElement pdf_element = document.getElementById("pdf-viewer");
if (pdf_element.isNull()) {
NOTREACHED();
return;
}
WebFrame* pdf_frame = pdf_element.document().frame();
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(pdf_frame, &pdf_element, &prepare)) {
LOG(ERROR) << "Failed to initialize print page settings";
return;
}
if (!UpdatePrintSettings(job_settings, false)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PRINT);
return;
}
if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
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: static int shm_mmap(struct file *file, struct vm_area_struct *vma)
{
struct shm_file_data *sfd = shm_file_data(file);
int ret;
ret = sfd->file->f_op->mmap(sfd->file, vma);
if (ret != 0)
return ret;
sfd->vm_ops = vma->vm_ops;
#ifdef CONFIG_MMU
WARN_ON(!sfd->vm_ops->fault);
#endif
vma->vm_ops = &shm_vm_ops;
shm_open(vma);
return ret;
}
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[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: int ssl_parse_certificate( ssl_context *ssl )
{
int ret;
size_t i, n;
SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->authmode == SSL_VERIFY_NONE )
{
ssl->verify_result = BADCERT_SKIP_VERIFY;
SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
ssl->state++;
return( 0 );
}
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
ssl->state++;
/*
* Check if the client sent an empty certificate
*/
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->in_msglen == 2 &&
ssl->in_msgtype == SSL_MSG_ALERT &&
ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT )
{
SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_OPTIONAL )
return( 0 );
else
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
}
}
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver != SSL_MINOR_VERSION_0 )
{
if( ssl->in_hslen == 7 &&
ssl->in_msgtype == SSL_MSG_HANDSHAKE &&
ssl->in_msg[0] == SSL_HS_CERTIFICATE &&
memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 )
{
SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_REQUIRED )
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
else
return( 0 );
}
}
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
/*
* Same message structure as in ssl_write_certificate()
*/
n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6];
if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc(
sizeof( x509_cert ) ) ) == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
sizeof( x509_cert ) ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) );
i = 7;
while( i < ssl->in_hslen )
{
if( ssl->in_msg[i] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
| (unsigned int) ssl->in_msg[i + 2];
i += 3;
if( n < 128 || i + n > ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
ret = x509parse_crt( ssl->session_negotiate->peer_cert, ssl->in_msg + i,
n );
if( ret != 0 )
{
SSL_DEBUG_RET( 1, " x509parse_crt", ret );
return( ret );
}
i += n;
}
SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
if( ssl->authmode != SSL_VERIFY_NONE )
{
if( ssl->ca_chain == NULL )
{
SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED );
}
ret = x509parse_verify( ssl->session_negotiate->peer_cert,
ssl->ca_chain, ssl->ca_crl,
ssl->peer_cn, &ssl->verify_result,
ssl->f_vrfy, ssl->p_vrfy );
if( ret != 0 )
SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
if( ssl->authmode != SSL_VERIFY_REQUIRED )
ret = 0;
}
SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
return( ret );
}
Commit Message: ssl_parse_certificate() now calls x509parse_crt_der() directly
CWE ID: CWE-20
Target: 1
Example 2:
Code: static enum bp_state update_schedule(enum bp_state state)
{
if (state == BP_WAIT)
return BP_WAIT;
if (state == BP_ECANCELED)
return BP_ECANCELED;
if (state == BP_DONE) {
balloon_stats.schedule_delay = 1;
balloon_stats.retry_count = 1;
return BP_DONE;
}
++balloon_stats.retry_count;
if (balloon_stats.max_retry_count != RETRY_UNLIMITED &&
balloon_stats.retry_count > balloon_stats.max_retry_count) {
balloon_stats.schedule_delay = 1;
balloon_stats.retry_count = 1;
return BP_ECANCELED;
}
balloon_stats.schedule_delay <<= 1;
if (balloon_stats.schedule_delay > balloon_stats.max_schedule_delay)
balloon_stats.schedule_delay = balloon_stats.max_schedule_delay;
return BP_EAGAIN;
}
Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free
commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream.
Instead of trying to allocate pages with GFP_USER in
add_ballooned_pages() check the available free memory via
si_mem_available(). GFP_USER is far less limiting memory exhaustion
than the test via si_mem_available().
This will avoid dom0 running out of memory due to excessive foreign
page mappings especially on ARM and on x86 in PVH mode, as those don't
have a pre-ballooned area which can be used for foreign mappings.
As the normal ballooning suffers from the same problem don't balloon
down more than si_mem_available() pages in one iteration. At the same
time limit the default maximum number of retries.
This is part of XSA-300.
Signed-off-by: Juergen Gross <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int __trace_puts(unsigned long ip, const char *str, int size)
{
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct print_entry *entry;
unsigned long irq_flags;
int alloc;
int pc;
if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
return 0;
pc = preempt_count();
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
alloc = sizeof(*entry) + size + 2; /* possible \n added */
local_save_flags(irq_flags);
buffer = global_trace.trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, alloc,
irq_flags, pc);
if (!event)
return 0;
entry = ring_buffer_event_data(event);
entry->ip = ip;
memcpy(&entry->buf, str, size);
/* Add a newline if necessary */
if (entry->buf[size - 1] != '\n') {
entry->buf[size] = '\n';
entry->buf[size + 1] = '\0';
} else
entry->buf[size] = '\0';
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(&global_trace, buffer, irq_flags, 4, pc, NULL);
return size;
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787
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 BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
void *params = malloc(size);
data.read(params, size);
status_t err;
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
free(params);
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: 3 uninitialized variables in IOMX.cpp
Uninitialized MetadataBufferType pointer in case:
SET_INPUT_SURFACE
STORE_META_DATA_IN_BUFFERS
CREATE_INPUT_SURFACE
Fix: initialize them to kMetadataBufferTypeInvalid
Bug: 26324358
Change-Id: Ib3bcac9bedc98bc65efa39f67cdbffbd90b374c9
CWE ID: CWE-119
Target: 1
Example 2:
Code: static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*property;
const StringInfo
*icc_profile;
Image
*base_image,
*next_image;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
channel_size,
channelLength,
layer_count,
layer_info_size,
length,
num_channels,
packet_size,
rounded_layer_info_size;
StringInfo
*bim_profile;
/*
Open image 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);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
layer_count=0;
layer_info_size=2;
base_image=GetNextImageInList(image);
if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL))
base_image=image;
next_image=base_image;
while ( next_image != NULL )
{
packet_size=next_image->depth > 8 ? 2UL : 1UL;
if (IsImageGray(next_image) != MagickFalse)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->storage_class == PseudoClass)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->colorspace != CMYKColorspace)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL;
else
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL;
channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);
layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :
16)+4*1+4+num_channels*channelLength);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
layer_info_size+=16;
else
{
size_t
layer_length;
layer_length=strlen(property);
layer_info_size+=8+layer_length+(4-(layer_length % 4));
}
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (layer_count == 0)
(void) SetPSDSize(&psd_info,image,0);
else
{
CompressionType
compression;
(void) SetPSDSize(&psd_info,image,layer_info_size+
(psd_info.version == 1 ? 8 : 16));
if ((layer_info_size/2) != ((layer_info_size+1)/2))
rounded_layer_info_size=layer_info_size+1;
else
rounded_layer_info_size=layer_info_size;
(void) SetPSDSize(&psd_info,image,rounded_layer_info_size);
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
(void) WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_count=1;
compression=base_image->compression;
for (next_image=base_image; next_image != NULL; )
{
next_image->compression=NoCompression;
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
packet_size=next_image->depth > 8 ? 2UL : 1UL;
channel_size=(unsigned int) ((packet_size*next_image->rows*
next_image->columns)+2);
if ((IsImageGray(next_image) != MagickFalse) ||
(next_image->storage_class == PseudoClass))
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
if (next_image->colorspace != CMYKColorspace)
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait ? 5 : 4));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,3);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
(void) WriteBlobByte(image,255); /* layer opacity */
(void) WriteBlobByte(image,0);
(void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
(void) WriteBlobByte(image,0);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
char
layer_name[MagickPathExtent];
(void) WriteBlobMSBLong(image,16);
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long)
layer_count++);
WritePascalString(image,layer_name,4);
}
else
{
size_t
label_length;
label_length=strlen(property);
(void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4-
(label_length % 4))+8));
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
WritePascalString(image,property,4);
}
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
while (next_image != NULL)
{
status=WriteImageChannels(&psd_info,image_info,image,next_image,
MagickTrue,exception);
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
base_image->compression=compression;
}
/*
Write composite image.
*/
if (status != MagickFalse)
status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse,
exception);
(void) CloseBlob(image);
return(status);
}
Commit Message: Added extra check to fix https://github.com/ImageMagick/ImageMagick/issues/93
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 ssize_t nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct nfs4_exception exception = { };
ssize_t ret;
do {
ret = __nfs4_get_acl_uncached(inode, buf, buflen);
if (ret >= 0)
break;
ret = nfs4_handle_exception(NFS_SERVER(inode), ret, &exception);
} while (exception.retry);
return ret;
}
Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached
_copy_from_pages() used to copy data from the temporary buffer to the
user passed buffer is passed the wrong size parameter when copying
data. res.acl_len contains both the bitmap and acl lenghts while
acl_len contains the acl length after adjusting for the bitmap size.
Signed-off-by: Sachin Prabhu <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
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: void usage()
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n");
fprintf (stderr, " or: ... | png2pnm [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n");
fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n");
fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: bool FocusInputAndSelectText() {
return ExecuteScript(interstitial_->GetMainFrame(), "focus_select_input()");
}
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 __perf_remove_from_context(void *info)
{
struct perf_event *event = info;
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
raw_spin_lock(&ctx->lock);
event_sched_out(event, cpuctx, ctx);
list_del_event(event, ctx);
if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
ctx->is_active = 0;
cpuctx->task_ctx = NULL;
}
raw_spin_unlock(&ctx->lock);
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
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: pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
if (olen != 2) {
ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen));
} else {
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
}
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
}
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
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), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void HeadlessPrintManager::Reset() {
printing_rfh_ = nullptr;
callback_.Reset();
print_params_.reset();
page_ranges_text_.clear();
ignore_invalid_page_ranges_ = false;
data_.clear();
}
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: static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
pipe_buf_get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
out:
kvfree(bufs);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
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: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fht8x8_ref;
}
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: OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo)
{
TIFF* tif=(TIFF*)cinfo->client_data;
OJPEGState* sp=(OJPEGState*)tif->tif_data;
void* mem=0;
uint32 len=0U;
if (OJPEGWriteStream(tif,&mem,&len)==0)
{
TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data");
jpeg_encap_unwind(tif);
}
sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len;
sp->libjpeg_jpeg_source_mgr.next_input_byte=mem;
return(1);
}
Commit Message: * libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in
OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611
CWE ID: CWE-369
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
{
MATLAB_KO:
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/598
CWE ID: CWE-617
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 iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = cxgb3_ofld_send(tdev, skb);
if (error < 0)
kfree_skb(skb);
return error;
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: JSObject* JSTestSerializedScriptValueInterface::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return JSTestSerializedScriptValueInterfacePrototype::create(exec->globalData(), globalObject, JSTestSerializedScriptValueInterfacePrototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype()));
}
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: 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 const char *set_protocols_honor_order(cmd_parms *cmd, void *dummy,
const char *arg)
{
core_server_config *conf =
ap_get_core_module_config(cmd->server->module_config);
const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
if (err) {
return err;
}
if (ap_cstr_casecmp(arg, "on") == 0) {
conf->protocols_honor_order = 1;
}
else if (ap_cstr_casecmp(arg, "off") == 0) {
conf->protocols_honor_order = 0;
}
else {
return "ProtocolsHonorOrder must be 'on' or 'off'";
}
return NULL;
}
Commit Message: core: Disallow Methods' registration at run time (.htaccess), they may be
used only if registered at init time (httpd.conf).
Calling ap_method_register() in children processes is not the right scope
since it won't be shared for all requests.
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68
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: 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_SPS_PPS_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: Return correct error code for slice header errors
Return ERROR_INV_SLICE_HDR_T instead of ERROR_INV_SPS_PPS_T for slice
header errors.
Bug: 34097915
Change-Id: I45d14a71f2322ff349058baaf65fb0f3c1140fba
CWE ID:
Target: 1
Example 2:
Code: int __glXDisp_CopyContext(__GLXclientState *cl, GLbyte *pc)
{
ClientPtr client = cl->client;
xGLXCopyContextReq *req = (xGLXCopyContextReq *) pc;
GLXContextID source = req->source;
GLXContextID dest = req->dest;
GLXContextTag tag = req->contextTag;
unsigned long mask = req->mask;
__GLXcontext *src, *dst;
int error;
if (!validGlxContext(cl->client, source, DixReadAccess, &src, &error))
return error;
if (!validGlxContext(cl->client, dest, DixWriteAccess, &dst, &error))
return error;
/*
** They must be in the same address space, and same screen.
** NOTE: no support for direct rendering contexts here.
*/
if (src->isDirect || dst->isDirect ||
(src->pGlxScreen != dst->pGlxScreen)) {
client->errorValue = source;
return BadMatch;
}
/*
** The destination context must not be current for any client.
*/
if (dst->isCurrent) {
client->errorValue = dest;
return BadAccess;
}
if (tag) {
__GLXcontext *tagcx = __glXLookupContextByTag(cl, tag);
if (!tagcx) {
return __glXError(GLXBadContextTag);
}
if (tagcx != src) {
/*
** This would be caused by a faulty implementation of the client
** library.
*/
return BadMatch;
}
/*
** In this case, glXCopyContext is in both GL and X streams, in terms
** of sequentiality.
*/
if (__glXForceCurrent(cl, tag, &error)) {
/*
** Do whatever is needed to make sure that all preceding requests
** in both streams are completed before the copy is executed.
*/
CALL_Finish( GET_DISPATCH(), () );
__GLX_NOTE_FLUSHED_CMDS(tagcx);
} else {
return error;
}
}
/*
** Issue copy. The only reason for failure is a bad mask.
*/
if (!(*dst->copy)(dst, src, mask)) {
client->errorValue = mask;
return BadValue;
}
return Success;
}
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* H264SwDecMalloc(u32 size) {
return malloc(size);
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static long pmcraid_ioctl_passthrough(
struct pmcraid_instance *pinstance,
unsigned int ioctl_cmd,
unsigned int buflen,
unsigned long arg
)
{
struct pmcraid_passthrough_ioctl_buffer *buffer;
struct pmcraid_ioarcb *ioarcb;
struct pmcraid_cmd *cmd;
struct pmcraid_cmd *cancel_cmd;
unsigned long request_buffer;
unsigned long request_offset;
unsigned long lock_flags;
void *ioasa;
u32 ioasc;
int request_size;
int buffer_size;
u8 access, direction;
int rc = 0;
/* If IOA reset is in progress, wait 10 secs for reset to complete */
if (pinstance->ioa_reset_in_progress) {
rc = wait_event_interruptible_timeout(
pinstance->reset_wait_q,
!pinstance->ioa_reset_in_progress,
msecs_to_jiffies(10000));
if (!rc)
return -ETIMEDOUT;
else if (rc < 0)
return -ERESTARTSYS;
}
/* If adapter is not in operational state, return error */
if (pinstance->ioa_state != IOA_STATE_OPERATIONAL) {
pmcraid_err("IOA is not operational\n");
return -ENOTTY;
}
buffer_size = sizeof(struct pmcraid_passthrough_ioctl_buffer);
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer) {
pmcraid_err("no memory for passthrough buffer\n");
return -ENOMEM;
}
request_offset =
offsetof(struct pmcraid_passthrough_ioctl_buffer, request_buffer);
request_buffer = arg + request_offset;
rc = __copy_from_user(buffer,
(struct pmcraid_passthrough_ioctl_buffer *) arg,
sizeof(struct pmcraid_passthrough_ioctl_buffer));
ioasa =
(void *)(arg +
offsetof(struct pmcraid_passthrough_ioctl_buffer, ioasa));
if (rc) {
pmcraid_err("ioctl: can't copy passthrough buffer\n");
rc = -EFAULT;
goto out_free_buffer;
}
request_size = buffer->ioarcb.data_transfer_length;
if (buffer->ioarcb.request_flags0 & TRANSFER_DIR_WRITE) {
access = VERIFY_READ;
direction = DMA_TO_DEVICE;
} else {
access = VERIFY_WRITE;
direction = DMA_FROM_DEVICE;
}
if (request_size > 0) {
rc = access_ok(access, arg, request_offset + request_size);
if (!rc) {
rc = -EFAULT;
goto out_free_buffer;
}
} else if (request_size < 0) {
rc = -EINVAL;
goto out_free_buffer;
}
/* check if we have any additional command parameters */
if (buffer->ioarcb.add_cmd_param_length > PMCRAID_ADD_CMD_PARAM_LEN) {
rc = -EINVAL;
goto out_free_buffer;
}
cmd = pmcraid_get_free_cmd(pinstance);
if (!cmd) {
pmcraid_err("free command block is not available\n");
rc = -ENOMEM;
goto out_free_buffer;
}
cmd->scsi_cmd = NULL;
ioarcb = &(cmd->ioa_cb->ioarcb);
/* Copy the user-provided IOARCB stuff field by field */
ioarcb->resource_handle = buffer->ioarcb.resource_handle;
ioarcb->data_transfer_length = buffer->ioarcb.data_transfer_length;
ioarcb->cmd_timeout = buffer->ioarcb.cmd_timeout;
ioarcb->request_type = buffer->ioarcb.request_type;
ioarcb->request_flags0 = buffer->ioarcb.request_flags0;
ioarcb->request_flags1 = buffer->ioarcb.request_flags1;
memcpy(ioarcb->cdb, buffer->ioarcb.cdb, PMCRAID_MAX_CDB_LEN);
if (buffer->ioarcb.add_cmd_param_length) {
ioarcb->add_cmd_param_length =
buffer->ioarcb.add_cmd_param_length;
ioarcb->add_cmd_param_offset =
buffer->ioarcb.add_cmd_param_offset;
memcpy(ioarcb->add_data.u.add_cmd_params,
buffer->ioarcb.add_data.u.add_cmd_params,
buffer->ioarcb.add_cmd_param_length);
}
/* set hrrq number where the IOA should respond to. Note that all cmds
* generated internally uses hrrq_id 0, exception to this is the cmd
* block of scsi_cmd which is re-used (e.g. cancel/abort), which uses
* hrrq_id assigned here in queuecommand
*/
ioarcb->hrrq_id = atomic_add_return(1, &(pinstance->last_message_id)) %
pinstance->num_hrrq;
if (request_size) {
rc = pmcraid_build_passthrough_ioadls(cmd,
request_size,
direction);
if (rc) {
pmcraid_err("couldn't build passthrough ioadls\n");
goto out_free_buffer;
}
}
/* If data is being written into the device, copy the data from user
* buffers
*/
if (direction == DMA_TO_DEVICE && request_size > 0) {
rc = pmcraid_copy_sglist(cmd->sglist,
request_buffer,
request_size,
direction);
if (rc) {
pmcraid_err("failed to copy user buffer\n");
goto out_free_sglist;
}
}
/* passthrough ioctl is a blocking command so, put the user to sleep
* until timeout. Note that a timeout value of 0 means, do timeout.
*/
cmd->cmd_done = pmcraid_internal_done;
init_completion(&cmd->wait_for_completion);
cmd->completion_req = 1;
pmcraid_info("command(%d) (CDB[0] = %x) for %x\n",
le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle) >> 2,
cmd->ioa_cb->ioarcb.cdb[0],
le32_to_cpu(cmd->ioa_cb->ioarcb.resource_handle));
spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
_pmcraid_fire_command(cmd);
spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
/* NOTE ! Remove the below line once abort_task is implemented
* in firmware. This line disables ioctl command timeout handling logic
* similar to IO command timeout handling, making ioctl commands to wait
* until the command completion regardless of timeout value specified in
* ioarcb
*/
buffer->ioarcb.cmd_timeout = 0;
/* If command timeout is specified put caller to wait till that time,
* otherwise it would be blocking wait. If command gets timed out, it
* will be aborted.
*/
if (buffer->ioarcb.cmd_timeout == 0) {
wait_for_completion(&cmd->wait_for_completion);
} else if (!wait_for_completion_timeout(
&cmd->wait_for_completion,
msecs_to_jiffies(buffer->ioarcb.cmd_timeout * 1000))) {
pmcraid_info("aborting cmd %d (CDB[0] = %x) due to timeout\n",
le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle >> 2),
cmd->ioa_cb->ioarcb.cdb[0]);
spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
cancel_cmd = pmcraid_abort_cmd(cmd);
spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
if (cancel_cmd) {
wait_for_completion(&cancel_cmd->wait_for_completion);
ioasc = cancel_cmd->ioa_cb->ioasa.ioasc;
pmcraid_return_cmd(cancel_cmd);
/* if abort task couldn't find the command i.e it got
* completed prior to aborting, return good completion.
* if command got aborted successfully or there was IOA
* reset due to abort task itself getting timedout then
* return -ETIMEDOUT
*/
if (ioasc == PMCRAID_IOASC_IOA_WAS_RESET ||
PMCRAID_IOASC_SENSE_KEY(ioasc) == 0x00) {
if (ioasc != PMCRAID_IOASC_GC_IOARCB_NOTFOUND)
rc = -ETIMEDOUT;
goto out_handle_response;
}
}
/* no command block for abort task or abort task failed to abort
* the IOARCB, then wait for 150 more seconds and initiate reset
* sequence after timeout
*/
if (!wait_for_completion_timeout(
&cmd->wait_for_completion,
msecs_to_jiffies(150 * 1000))) {
pmcraid_reset_bringup(cmd->drv_inst);
rc = -ETIMEDOUT;
}
}
out_handle_response:
/* copy entire IOASA buffer and return IOCTL success.
* If copying IOASA to user-buffer fails, return
* EFAULT
*/
if (copy_to_user(ioasa, &cmd->ioa_cb->ioasa,
sizeof(struct pmcraid_ioasa))) {
pmcraid_err("failed to copy ioasa buffer to user\n");
rc = -EFAULT;
}
/* If the data transfer was from device, copy the data onto user
* buffers
*/
else if (direction == DMA_FROM_DEVICE && request_size > 0) {
rc = pmcraid_copy_sglist(cmd->sglist,
request_buffer,
request_size,
direction);
if (rc) {
pmcraid_err("failed to copy user buffer\n");
rc = -EFAULT;
}
}
out_free_sglist:
pmcraid_release_passthrough_ioadls(cmd, request_size, direction);
pmcraid_return_cmd(cmd);
out_free_buffer:
kfree(buffer);
return rc;
}
Commit Message: [SCSI] pmcraid: reject negative request size
There's a code path in pmcraid that can be reached via device ioctl that
causes all sorts of ugliness, including heap corruption or triggering the
OOM killer due to consecutive allocation of large numbers of pages.
First, the user can call pmcraid_chr_ioctl(), with a type
PMCRAID_PASSTHROUGH_IOCTL. This calls through to
pmcraid_ioctl_passthrough(). Next, a pmcraid_passthrough_ioctl_buffer
is copied in, and the request_size variable is set to
buffer->ioarcb.data_transfer_length, which is an arbitrary 32-bit
signed value provided by the user. If a negative value is provided
here, bad things can happen. For example,
pmcraid_build_passthrough_ioadls() is called with this request_size,
which immediately calls pmcraid_alloc_sglist() with a negative size.
The resulting math on allocating a scatter list can result in an
overflow in the kzalloc() call (if num_elem is 0, the sglist will be
smaller than expected), or if num_elem is unexpectedly large the
subsequent loop will call alloc_pages() repeatedly, a high number of
pages will be allocated and the OOM killer might be invoked.
It looks like preventing this value from being negative in
pmcraid_ioctl_passthrough() would be sufficient.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: James Bottomley <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int decode_attr_mounted_on_fileid(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *fileid)
{
__be32 *p;
*fileid = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_MOUNTED_ON_FILEID - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_MOUNTED_ON_FILEID)) {
READ_BUF(8);
READ64(*fileid);
bitmap[1] &= ~FATTR4_WORD1_MOUNTED_ON_FILEID;
}
dprintk("%s: fileid=%Lu\n", __func__, (unsigned long long)*fileid);
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: archive_read_format_iso9660_options(struct archive_read *a,
const char *key, const char *val)
{
struct iso9660 *iso9660;
iso9660 = (struct iso9660 *)(a->format->data);
if (strcmp(key, "joliet") == 0) {
if (val == NULL || strcmp(val, "off") == 0 ||
strcmp(val, "ignore") == 0 ||
strcmp(val, "disable") == 0 ||
strcmp(val, "0") == 0)
iso9660->opt_support_joliet = 0;
else
iso9660->opt_support_joliet = 1;
return (ARCHIVE_OK);
}
if (strcmp(key, "rockridge") == 0 ||
strcmp(key, "Rockridge") == 0) {
iso9660->opt_support_rockridge = val != NULL;
return (ARCHIVE_OK);
}
/* Note: The "warn" return is just to inform the options
* supervisor that we didn't handle it. It will generate
* a suitable error if no one used this option. */
return (ARCHIVE_WARN);
}
Commit Message: Issue 717: Fix integer overflow when computing location of volume descriptor
The multiplication here defaulted to 'int' but calculations
of file positions should always use int64_t. A simple cast
suffices to fix this since the base location is always 32 bits
for ISO, so multiplying by the sector size will never overflow
a 64-bit integer.
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: main(int argc, char **argv)
{
int i, valgrind_mode = 0;
int valgrind_tool = 0;
int valgrind_gdbserver = 0;
char buf[16384], **args, *home;
char valgrind_path[PATH_MAX] = "";
const char *valgrind_log = NULL;
Eina_Bool really_know = EINA_FALSE;
struct sigaction action;
pid_t child = -1;
#ifdef E_CSERVE
pid_t cs_child = -1;
Eina_Bool cs_use = EINA_FALSE;
#endif
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
Eina_Bool restart = EINA_TRUE;
#endif
unsetenv("NOTIFY_SOCKET");
/* Setup USR1 to detach from the child process and let it get gdb by advanced users */
action.sa_sigaction = _sigusr1;
action.sa_flags = SA_RESETHAND;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
eina_init();
/* reexcute myself with dbus-launch if dbus-launch is not running yet */
if ((!getenv("DBUS_SESSION_BUS_ADDRESS")) &&
(!getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")))
{
char **dbus_argv;
dbus_argv = alloca((argc + 3) * sizeof (char *));
dbus_argv[0] = "dbus-launch";
dbus_argv[1] = "--exit-with-session";
copy_args(dbus_argv + 2, argv, argc);
dbus_argv[2 + argc] = NULL;
execvp("dbus-launch", dbus_argv);
}
prefix_determine(argv[0]);
env_set("E_START", argv[0]);
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-valgrind-gdb"))
valgrind_gdbserver = 1;
else if (!strncmp(argv[i], "-valgrind", sizeof("-valgrind") - 1))
{
const char *val = argv[i] + sizeof("-valgrind") - 1;
if (*val == '\0') valgrind_mode = 1;
else if (*val == '-')
{
val++;
if (!strncmp(val, "log-file=", sizeof("log-file=") - 1))
{
valgrind_log = val + sizeof("log-file=") - 1;
if (*valgrind_log == '\0') valgrind_log = NULL;
}
}
else if (*val == '=')
{
val++;
if (!strcmp(val, "all")) valgrind_mode = VALGRIND_MODE_ALL;
else valgrind_mode = atoi(val);
}
else
printf("Unknown valgrind option: %s\n", argv[i]);
}
else if (!strcmp(argv[i], "-display"))
{
i++;
env_set("DISPLAY", argv[i]);
}
else if (!strcmp(argv[i], "-massif"))
valgrind_tool = 1;
else if (!strcmp(argv[i], "-callgrind"))
valgrind_tool = 2;
else if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf
(
"Options:\n"
"\t-valgrind[=MODE]\n"
"\t\tRun enlightenment from inside valgrind, mode is OR of:\n"
"\t\t 1 = plain valgrind to catch crashes (default)\n"
"\t\t 2 = trace children (thumbnailer, efm slaves, ...)\n"
"\t\t 4 = check leak\n"
"\t\t 8 = show reachable after processes finish.\n"
"\t\t all = all of above\n"
"\t-massif\n"
"\t\tRun enlightenment from inside massif valgrind tool.\n"
"\t-callgrind\n"
"\t\tRun enlightenment from inside callgrind valgrind tool.\n"
"\t-valgrind-log-file=<FILENAME>\n"
"\t\tSave valgrind log to file, see valgrind's --log-file for details.\n"
"\n"
"Please run:\n"
"\tenlightenment %s\n"
"for more options.\n",
argv[i]);
exit(0);
}
else if (!strcmp(argv[i], "-i-really-know-what-i-am-doing-and-accept-full-responsibility-for-it"))
really_know = EINA_TRUE;
}
if (really_know)
_env_path_append("PATH", eina_prefix_bin_get(pfx));
else
_env_path_prepend("PATH", eina_prefix_bin_get(pfx));
if (valgrind_mode || valgrind_tool)
{
if (!find_valgrind(valgrind_path, sizeof(valgrind_path)))
{
printf("E - valgrind required but no binary found! Ignoring request.\n");
valgrind_mode = 0;
}
}
printf("E - PID=%i, valgrind=%d", getpid(), valgrind_mode);
if (valgrind_mode)
{
printf(" valgrind-command='%s'", valgrind_path);
if (valgrind_log) printf(" valgrind-log-file='%s'", valgrind_log);
}
putchar('\n');
/* mtrack memory tracker support */
home = getenv("HOME");
if (home)
{
FILE *f;
/* if you have ~/.e-mtrack, then the tracker will be enabled
* using the content of this file as the path to the mtrack.so
* shared object that is the mtrack preload */
snprintf(buf, sizeof(buf), "%s/.e-mtrack", home);
f = fopen(buf, "r");
if (f)
{
if (fgets(buf, sizeof(buf), f))
{
int len = strlen(buf);
if ((len > 1) && (buf[len - 1] == '\n'))
{
buf[len - 1] = 0;
len--;
}
env_set("LD_PRELOAD", buf);
env_set("MTRACK", "track");
env_set("E_START_MTRACK", "track");
snprintf(buf, sizeof(buf), "%s/.e-mtrack.log", home);
env_set("MTRACK_TRACE_FILE", buf);
}
fclose(f);
}
}
/* run e directly now */
snprintf(buf, sizeof(buf), "%s/enlightenment", eina_prefix_bin_get(pfx));
args = alloca((argc + 2 + VALGRIND_MAX_ARGS) * sizeof(char *));
i = valgrind_append(args, valgrind_gdbserver, valgrind_mode, valgrind_tool, valgrind_path, valgrind_log);
args[i++] = buf;
copy_args(args + i, argv + 1, argc - 1);
args[i + argc - 1] = NULL;
if (valgrind_tool || valgrind_mode)
really_know = EINA_TRUE;
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || (defined (__MACH__) && defined (__APPLE__))
execv(args[0], args);
#endif
/* not run at the moment !! */
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
#ifdef E_CSERVE
if (getenv("E_CSERVE"))
{
cs_use = EINA_TRUE;
cs_child = _cserve2_start();
}
#endif
/* Now looping until */
while (restart)
{
stop_ptrace = EINA_FALSE;
child = fork();
if (child < 0) /* failed attempt */
return -1;
else if (child == 0)
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* in the child */
ptrace(PT_TRACE_ME, 0, NULL, NULL);
#endif
execv(args[0], args);
return 0; /* We failed, 0 mean normal exit from E with no restart or crash so let exit */
}
else
{
env_set("E_RESTART", "1");
/* in the parent */
pid_t result;
int status;
Eina_Bool done = EINA_FALSE;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_ATTACH, child, NULL, NULL);
result = waitpid(child, &status, 0);
if ((!really_know) && (!stop_ptrace))
{
if (WIFSTOPPED(status))
ptrace(PT_CONTINUE, child, NULL, NULL);
}
#endif
while (!done)
{
Eina_Bool remember_sigill = EINA_FALSE;
Eina_Bool remember_sigusr1 = EINA_FALSE;
result = waitpid(child, &status, WNOHANG);
if (!result)
{
/* Wait for evas_cserve2 and E */
result = waitpid(-1, &status, 0);
}
if (result == child)
{
if ((WIFSTOPPED(status)) && (!stop_ptrace))
{
char buffer[4096];
char *backtrace_str = NULL;
siginfo_t sig;
int r = 0;
int back;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
r = ptrace(PT_GETSIGINFO, child, NULL, &sig);
#endif
back = r == 0 &&
sig.si_signo != SIGTRAP ? sig.si_signo : 0;
if (sig.si_signo == SIGUSR1)
{
if (remember_sigill)
remember_sigusr1 = EINA_TRUE;
}
else if (sig.si_signo == SIGILL)
{
remember_sigill = EINA_TRUE;
}
else
{
remember_sigill = EINA_FALSE;
}
if (r != 0 ||
(sig.si_signo != SIGSEGV &&
sig.si_signo != SIGFPE &&
sig.si_signo != SIGABRT))
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_CONTINUE, child, NULL, back);
#endif
continue;
}
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* E18 should be in pause, we can detach */
ptrace(PT_DETACH, child, NULL, back);
#endif
/* And call gdb if available */
r = 0;
if (home)
{
/* call e_sys gdb */
snprintf(buffer, 4096,
"%s/enlightenment/utils/enlightenment_sys gdb %i %s/.e-crashdump.txt",
eina_prefix_lib_get(pfx),
child,
home);
r = system(buffer);
r = system(buffer);
fprintf(stderr, "called gdb with '%s' = %i\n",
buffer, WEXITSTATUS(r));
snprintf(buffer, 4096,
"%s/.e-crashdump.txt",
home);
backtrace_str = strdup(buffer);
r = WEXITSTATUS(r);
}
/* call e_alert */
snprintf(buffer, 4096,
backtrace_str ?
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i" :
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i",
eina_prefix_lib_get(pfx),
sig.si_signo == SIGSEGV && remember_sigusr1 ? SIGILL : sig.si_signo,
child,
backtrace_str,
r);
r = system(buffer);
/* kill e */
kill(child, SIGKILL);
if (WEXITSTATUS(r) != 1)
{
restart = EINA_FALSE;
}
}
else if (!WIFEXITED(status))
{
done = EINA_TRUE;
}
else if (stop_ptrace)
{
done = EINA_TRUE;
}
}
else if (result == -1)
{
if (errno != EINTR)
{
done = EINA_TRUE;
restart = EINA_FALSE;
}
else
{
if (stop_ptrace)
{
kill(child, SIGSTOP);
usleep(200000);
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_DETACH, child, NULL, NULL);
#endif
}
}
}
#ifdef E_CSERVE
else if (cs_use && (result == cs_child))
{
if (WIFSIGNALED(status))
{
printf("E - cserve2 terminated with signal %d\n",
WTERMSIG(status));
cs_child = _cserve2_start();
}
else if (WIFEXITED(status))
{
printf("E - cserve2 exited with code %d\n",
WEXITSTATUS(status));
cs_child = -1;
}
}
#endif
}
}
}
#endif
#ifdef E_CSERVE
if (cs_child > 0)
{
pid_t result;
int status;
alarm(2);
kill(cs_child, SIGINT);
result = waitpid(cs_child, &status, 0);
if (result != cs_child)
{
printf("E - cserve2 did not shutdown in 2 seconds, killing!\n");
kill(cs_child, SIGKILL);
}
}
#endif
return -1;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Browser::ActiveTabChanged(TabContentsWrapper* old_contents,
TabContentsWrapper* new_contents,
int index,
bool user_gesture) {
if (user_gesture && new_contents->tab_contents()->crashed_status() ==
base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
if (parsed_command_line.HasSwitch(switches::kReloadKilledTabs)) {
Reload(CURRENT_TAB);
return;
}
}
if (!chrome_updater_factory_.empty() && old_contents)
ProcessPendingUIUpdates();
UpdateToolbar(true);
UpdateReloadStopState(new_contents->tab_contents()->IsLoading(), true);
UpdateCommandsForTabState();
StatusBubble* status_bubble = GetStatusBubble();
if (status_bubble) {
status_bubble->Hide();
status_bubble->SetStatus(GetSelectedTabContentsWrapper()->GetStatusText());
}
if (HasFindBarController()) {
find_bar_controller_->ChangeTabContents(new_contents);
find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
}
SessionService* session_service =
SessionServiceFactory::GetForProfileIfExisting(profile_);
if (session_service && !tab_handler_->GetTabStripModel()->closing_all()) {
session_service->SetSelectedTabInWindow(
session_id(), tab_handler_->GetTabStripModel()->active_index());
}
UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
}
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: int randseed(bool srand_it)
{
/*
srand pre-seed function based on /dev/urandom
*/
unsigned int seed=time(NULL)+getpid();
FILE *f;
f = fopen("/dev/urandom", "r");
if (f) {
int ret = fread(&seed, sizeof(seed), 1, f);
if (ret != 1)
DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno));
fclose(f);
}
if (srand_it)
srand(seed);
return seed;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
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 sycc444_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
unsigned int maxw, maxh, max, i;
int offset, upb;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i = 0U; i < max; ++i)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++cb; ++cr; ++r; ++g; ++b;
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc444_to_rgb() */
Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745)
42x Images with an odd x0/y0 lead to subsampled component starting at the
2nd column/line.
That is offset = comp->dx * comp->x0 - image->x0 = 1
Fix #726
CWE ID: CWE-125
Target: 1
Example 2:
Code: LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
{
if (logicalWidthLength.type() == FillAvailable)
return fillAvailableMeasure(availableLogicalWidth);
LayoutUnit minLogicalWidth = 0;
LayoutUnit maxLogicalWidth = 0;
computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
if (logicalWidthLength.type() == MinContent)
return minLogicalWidth + borderAndPadding;
if (logicalWidthLength.type() == MaxContent)
return maxLogicalWidth + borderAndPadding;
if (logicalWidthLength.type() == FitContent) {
minLogicalWidth += borderAndPadding;
maxLogicalWidth += borderAndPadding;
return max(minLogicalWidth, min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
}
ASSERT_NOT_REACHED();
return 0;
}
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: SPL_METHOD(SplFileObject, fseek)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long pos, whence = SEEK_SET;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) {
return;
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence));
} /* }}} */
/* {{{ proto int SplFileObject::fgetc()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int virtnet_probe(struct virtio_device *vdev)
{
int i, err;
struct net_device *dev;
struct virtnet_info *vi;
u16 max_queue_pairs;
if (!vdev->config->get) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
if (!virtnet_validate_features(vdev))
return -EINVAL;
/* Find if host supports multiqueue virtio_net device */
err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
struct virtio_net_config,
max_virtqueue_pairs, &max_queue_pairs);
/* We need at least 2 queue's */
if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
max_queue_pairs = 1;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
dev->ethtool_ops = &virtnet_ethtool_ops;
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (csum)
dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
dev->features |= NETIF_F_GSO_ROBUST;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
dev->features |= NETIF_F_RXCSUM;
dev->vlan_features = dev->features;
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
virtio_cread_bytes(vdev,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
else
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
for_each_possible_cpu(i) {
struct virtnet_stats *virtnet_stats;
virtnet_stats = per_cpu_ptr(vi->stats, i);
u64_stats_init(&virtnet_stats->tx_syncp);
u64_stats_init(&virtnet_stats->rx_syncp);
}
INIT_WORK(&vi->config_work, virtnet_config_changed_work);
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
vi->hdr_len = sizeof(struct virtio_net_hdr);
if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->any_header_sg = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
vi->has_cvq = true;
if (vi->any_header_sg)
dev->needed_headroom = vi->hdr_len;
/* Use single tx/rx queue pair as default */
vi->curr_queue_pairs = 1;
vi->max_queue_pairs = max_queue_pairs;
/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
err = init_vqs(vi);
if (err)
goto free_stats;
#ifdef CONFIG_SYSFS
if (vi->mergeable_rx_bufs)
dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
#endif
netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
virtio_device_ready(vdev);
/* Last of all, set up some receive buffers. */
for (i = 0; i < vi->curr_queue_pairs; i++) {
try_fill_recv(vi, &vi->rq[i], GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->rq[i].vq->num_free ==
virtqueue_get_vring_size(vi->rq[i].vq)) {
free_unused_bufs(vi);
err = -ENOMEM;
goto free_recv_bufs;
}
}
vi->nb.notifier_call = &virtnet_cpu_callback;
err = register_hotcpu_notifier(&vi->nb);
if (err) {
pr_debug("virtio_net: registering cpu notifier failed\n");
goto free_recv_bufs;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
schedule_work(&vi->config_work);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
dev->name, max_queue_pairs);
return 0;
free_recv_bufs:
vi->vdev->config->reset(vdev);
free_receive_bufs(vi);
unregister_netdev(dev);
free_vqs:
cancel_delayed_work_sync(&vi->refill);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
Commit Message: virtio-net: drop NETIF_F_FRAGLIST
virtio declares support for NETIF_F_FRAGLIST, but assumes
that there are at most MAX_SKB_FRAGS + 2 fragments which isn't
always true with a fraglist.
A longer fraglist in the skb will make the call to skb_to_sgvec overflow
the sg array, leading to memory corruption.
Drop NETIF_F_FRAGLIST so we only get what we can handle.
Cc: Michael S. Tsirkin <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int wa_fill_descr(struct wahc *wa)
{
int result;
struct device *dev = &wa->usb_iface->dev;
char *itr;
struct usb_device *usb_dev = wa->usb_dev;
struct usb_descriptor_header *hdr;
struct usb_wa_descriptor *wa_descr;
size_t itr_size, actconfig_idx;
actconfig_idx = (usb_dev->actconfig - usb_dev->config) /
sizeof(usb_dev->config[0]);
itr = usb_dev->rawdescriptors[actconfig_idx];
itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength);
while (itr_size >= sizeof(*hdr)) {
hdr = (struct usb_descriptor_header *) itr;
dev_dbg(dev, "Extra device descriptor: "
"type %02x/%u bytes @ %zu (%zu left)\n",
hdr->bDescriptorType, hdr->bLength,
(itr - usb_dev->rawdescriptors[actconfig_idx]),
itr_size);
if (hdr->bDescriptorType == USB_DT_WIRE_ADAPTER)
goto found;
itr += hdr->bLength;
itr_size -= hdr->bLength;
}
dev_err(dev, "cannot find Wire Adapter Class descriptor\n");
return -ENODEV;
found:
result = -EINVAL;
if (hdr->bLength > itr_size) { /* is it available? */
dev_err(dev, "incomplete Wire Adapter Class descriptor "
"(%zu bytes left, %u needed)\n",
itr_size, hdr->bLength);
goto error;
}
if (hdr->bLength < sizeof(*wa->wa_descr)) {
dev_err(dev, "short Wire Adapter Class descriptor\n");
goto error;
}
wa->wa_descr = wa_descr = (struct usb_wa_descriptor *) hdr;
if (le16_to_cpu(wa_descr->bcdWAVersion) > 0x0100)
dev_warn(dev, "Wire Adapter v%d.%d newer than groked v1.0\n",
(le16_to_cpu(wa_descr->bcdWAVersion) & 0xff00) >> 8,
le16_to_cpu(wa_descr->bcdWAVersion) & 0x00ff);
result = 0;
error:
return result;
}
Commit Message: USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: safe_fprintf(FILE *f, const char *fmt, ...)
{
char fmtbuff_stack[256]; /* Place to format the printf() string. */
char outbuff[256]; /* Buffer for outgoing characters. */
char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
int fmtbuff_length;
int length, n;
va_list ap;
const char *p;
unsigned i;
wchar_t wc;
char try_wc;
/* Use a stack-allocated buffer if we can, for speed and safety. */
fmtbuff_heap = NULL;
fmtbuff_length = sizeof(fmtbuff_stack);
fmtbuff = fmtbuff_stack;
/* Try formatting into the stack buffer. */
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
/* If the result was too large, allocate a buffer on the heap. */
while (length < 0 || length >= fmtbuff_length) {
if (length >= fmtbuff_length)
fmtbuff_length = length+1;
else if (fmtbuff_length < 8192)
fmtbuff_length *= 2;
else if (fmtbuff_length < 1000000)
fmtbuff_length += fmtbuff_length / 4;
else {
length = fmtbuff_length;
fmtbuff_heap[length-1] = '\0';
break;
}
free(fmtbuff_heap);
fmtbuff_heap = malloc(fmtbuff_length);
/* Reformat the result into the heap buffer if we can. */
if (fmtbuff_heap != NULL) {
fmtbuff = fmtbuff_heap;
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
} else {
/* Leave fmtbuff pointing to the truncated
* string in fmtbuff_stack. */
length = sizeof(fmtbuff_stack) - 1;
break;
}
}
/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
* more portable, so we use that here instead. */
if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
/* mbtowc() should never fail in practice, but
* handle the theoretical error anyway. */
free(fmtbuff_heap);
return;
}
/* Write data, expanding unprintable characters. */
p = fmtbuff;
i = 0;
try_wc = 1;
while (*p != '\0') {
/* Convert to wide char, test if the wide
* char is printable in the current locale. */
if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
length -= n;
if (iswprint(wc) && wc != L'\\') {
/* Printable, copy the bytes through. */
while (n-- > 0)
outbuff[i++] = *p++;
} else {
/* Not printable, format the bytes. */
while (n-- > 0)
i += (unsigned)bsdtar_expand_char(
outbuff, i, *p++);
}
} else {
/* After any conversion failure, don't bother
* trying to convert the rest. */
i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
try_wc = 0;
}
/* If our output buffer is full, dump it and keep going. */
if (i > (sizeof(outbuff) - 20)) {
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
i = 0;
}
}
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
/* If we allocated a heap-based formatting buffer, free it now. */
free(fmtbuff_heap);
}
Commit Message: Issue #767: Buffer overflow printing a filename
The safe_fprintf function attempts to ensure clean output for an
arbitrary sequence of bytes by doing a trial conversion of the
multibyte characters to wide characters -- if the resulting wide
character is printable then we pass through the corresponding bytes
unaltered, otherwise, we convert them to C-style ASCII escapes.
The stack trace in Issue #767 suggest that the 20-byte buffer
was getting overflowed trying to format a non-printable multibyte
character. This should only happen if there is a valid multibyte
character of more than 5 bytes that was unprintable. (Each byte
would get expanded to a four-charcter octal-style escape of the form
"\123" resulting in >20 characters for the >5 byte multibyte character.)
I've not been able to reproduce this, but have expanded the conversion
buffer to 128 bytes on the belief that no multibyte character set
has a single character of more than 32 bytes.
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: bool ContainOnlyOneKeyboardLayout(
const ImeConfigValue& value) {
return (value.type == ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
chromeos::input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
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: ScriptPromise BluetoothRemoteGATTService::getCharacteristics(
ScriptState* scriptState,
const StringOrUnsignedLong& characteristic,
ExceptionState& exceptionState) {
String characteristicUUID =
BluetoothUUID::getCharacteristic(characteristic, exceptionState);
if (exceptionState.hadException())
return exceptionState.reject(scriptState);
return getCharacteristicsImpl(
scriptState, mojom::blink::WebBluetoothGATTQueryQuantity::MULTIPLE,
characteristicUUID);
}
Commit Message: Allow serialization of empty bluetooth uuids.
This change allows the passing WTF::Optional<String> types as
bluetooth.mojom.UUID optional parameter without needing to ensure the passed
object isn't empty.
BUG=None
R=juncai, dcheng
Review-Url: https://codereview.chromium.org/2646613003
Cr-Commit-Position: refs/heads/master@{#445809}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx,
const unsigned char *ax)
{
#ifdef USE_AMD64_ASM
return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#elif defined(USE_ARM_ASM)
return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#else
return do_decrypt_fn (ctx, bx, ax);
#endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/
}
Commit Message: AES: move look-up tables to .data section and unshare between processes
* cipher/rijndael-internal.h (ATTR_ALIGNED_64): New.
* cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure.
(enc_tables): New structure for encryption table with counters before
and after.
(encT): New macro.
(dec_tables): Add counters before and after encryption table; Move
from .rodata to .data section.
(do_encrypt): Change 'encT' to 'enc_tables.T'.
(do_decrypt): Change '&dec_tables' to 'dec_tables.T'.
* cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input
with length not multiple of 256.
(prefetch_enc, prefetch_dec): Modify pre- and post-table counters
to unshare look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() {
return brightness_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 readonlyDOMTimeStampAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectPythonV8Internal::readonlyDOMTimeStampAttributeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsImpl::RendererUnresponsive(
RenderWidgetHostImpl* render_widget_host) {
if (render_widget_host != GetRenderViewHost()->GetWidget())
return;
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(GetRenderViewHost()->GetMainFrame());
if (DevToolsAgentHost::IsDebuggerAttached(this))
return;
if (rfhi->is_waiting_for_beforeunload_ack() ||
rfhi->IsWaitingForUnloadACK()) {
GetRenderViewHost()->set_sudden_termination_allowed(true);
if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
return;
bool close = true;
if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
delegate_->BeforeUnloadFired(this, true, &close);
}
if (close)
Close();
return;
}
if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
return;
if (delegate_)
delegate_->RendererUnresponsive(this);
}
Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted
BUG=583718
Review URL: https://codereview.chromium.org/1685343004
Cr-Commit-Position: refs/heads/master@{#375700}
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 int load_script(struct linux_binprm *bprm)
{
const char *i_arg, *i_name;
char *cp;
struct file *file;
char interp[BINPRM_BUF_SIZE];
int retval;
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
return -ENOEXEC;
/*
* This section does the #! interpretation.
* Sorta complicated, but hopefully it will work. -TYT
*/
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
bprm->buf[BINPRM_BUF_SIZE - 1] = '\0';
if ((cp = strchr(bprm->buf, '\n')) == NULL)
cp = bprm->buf+BINPRM_BUF_SIZE-1;
*cp = '\0';
while (cp > bprm->buf) {
cp--;
if ((*cp == ' ') || (*cp == '\t'))
*cp = '\0';
else
break;
}
for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++);
if (*cp == '\0')
return -ENOEXEC; /* No interpreter name found */
i_name = cp;
i_arg = NULL;
for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++)
/* nothing */ ;
while ((*cp == ' ') || (*cp == '\t'))
*cp++ = '\0';
if (*cp)
i_arg = cp;
strcpy (interp, i_name);
/*
* OK, we've parsed out the interpreter name and
* (optional) argument.
* Splice in (1) the interpreter's name for argv[0]
* (2) (optional) argument to interpreter
* (3) filename of shell script (replace argv[0])
*
* This is done in reverse order, because of how the
* user environment and arguments are stored.
*/
retval = remove_arg_zero(bprm);
if (retval)
return retval;
retval = copy_strings_kernel(1, &bprm->interp, bprm);
if (retval < 0) return retval;
bprm->argc++;
if (i_arg) {
retval = copy_strings_kernel(1, &i_arg, bprm);
if (retval < 0) return retval;
bprm->argc++;
}
retval = copy_strings_kernel(1, &i_name, bprm);
if (retval) return retval;
bprm->argc++;
bprm->interp = interp;
/*
* OK, now restart the process with the interpreter's dentry.
*/
file = open_exec(interp);
if (IS_ERR(file))
return PTR_ERR(file);
bprm->file = file;
retval = prepare_binprm(bprm);
if (retval < 0)
return retval;
return search_binary_handler(bprm);
}
Commit Message: exec: do not leave bprm->interp on stack
If a series of scripts are executed, each triggering module loading via
unprintable bytes in the script header, kernel stack contents can leak
into the command line.
Normally execution of binfmt_script and binfmt_misc happens recursively.
However, when modules are enabled, and unprintable bytes exist in the
bprm->buf, execution will restart after attempting to load matching
binfmt modules. Unfortunately, the logic in binfmt_script and
binfmt_misc does not expect to get restarted. They leave bprm->interp
pointing to their local stack. This means on restart bprm->interp is
left pointing into unused stack memory which can then be copied into the
userspace argv areas.
After additional study, it seems that both recursion and restart remains
the desirable way to handle exec with scripts, misc, and modules. As
such, we need to protect the changes to interp.
This changes the logic to require allocation for any changes to the
bprm->interp. To avoid adding a new kmalloc to every exec, the default
value is left as-is. Only when passing through binfmt_script or
binfmt_misc does an allocation take place.
For a proof of concept, see DoTest.sh from:
http://www.halfdog.net/Security/2012/LinuxKernelBinfmtScriptStackDataDisclosure/
Signed-off-by: Kees Cook <[email protected]>
Cc: halfdog <[email protected]>
Cc: P J P <[email protected]>
Cc: Alexander Viro <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int mqueue_create(struct inode *dir, struct dentry *dentry,
umode_t mode, bool excl)
{
struct inode *inode;
struct mq_attr *attr = dentry->d_fsdata;
int error;
struct ipc_namespace *ipc_ns;
spin_lock(&mq_lock);
ipc_ns = __get_ns_from_inode(dir);
if (!ipc_ns) {
error = -EACCES;
goto out_unlock;
}
if (ipc_ns->mq_queues_count >= ipc_ns->mq_queues_max &&
!capable(CAP_SYS_RESOURCE)) {
error = -ENOSPC;
goto out_unlock;
}
ipc_ns->mq_queues_count++;
spin_unlock(&mq_lock);
inode = mqueue_get_inode(dir->i_sb, ipc_ns, mode, attr);
if (IS_ERR(inode)) {
error = PTR_ERR(inode);
spin_lock(&mq_lock);
ipc_ns->mq_queues_count--;
goto out_unlock;
}
put_ipc_ns(ipc_ns);
dir->i_size += DIRENT_SIZE;
dir->i_ctime = dir->i_mtime = dir->i_atime = current_time(dir);
d_instantiate(dentry, inode);
dget(dentry);
return 0;
out_unlock:
spin_unlock(&mq_lock);
if (ipc_ns)
put_ipc_ns(ipc_ns);
return error;
}
Commit Message: mqueue: fix a use-after-free in sys_mq_notify()
The retry logic for netlink_attachskb() inside sys_mq_notify()
is nasty and vulnerable:
1) The sock refcnt is already released when retry is needed
2) The fd is controllable by user-space because we already
release the file refcnt
so we when retry but the fd has been just closed by user-space
during this small window, we end up calling netlink_detachskb()
on the error path which releases the sock again, later when
the user-space closes this socket a use-after-free could be
triggered.
Setting 'sock' to NULL here should be sufficient to fix it.
Reported-by: GeneBlue <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
{
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_map *em = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
u64 end;
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
read_unlock(&em_tree->lock);
if (em) {
end = extent_map_end(em);
free_extent_map(em);
if (end - offset > thresh)
return 0;
}
/* if we already have a nice delalloc here, just stop */
thresh /= 2;
end = count_range_bits(io_tree, &offset, offset + thresh,
thresh, EXTENT_DELALLOC, 1);
if (end >= thresh)
return 0;
return 1;
}
Commit Message: Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
Commit Message: ext4: avoid hang when mounting non-journal filesystems with orphan list
When trying to mount a file system which does not contain a journal,
but which does have a orphan list containing an inode which needs to
be truncated, the mount call with hang forever in
ext4_orphan_cleanup() because ext4_orphan_del() will return
immediately without removing the inode from the orphan list, leading
to an uninterruptible loop in kernel code which will busy out one of
the CPU's on the system.
This can be trivially reproduced by trying to mount the file system
found in tests/f_orphan_extents_inode/image.gz from the e2fsprogs
source tree. If a malicious user were to put this on a USB stick, and
mount it on a Linux desktop which has automatic mounts enabled, this
could be considered a potential denial of service attack. (Not a big
deal in practice, but professional paranoids worry about such things,
and have even been known to allocate CVE numbers for such problems.)
Signed-off-by: "Theodore Ts'o" <[email protected]>
Reviewed-by: Zheng Liu <[email protected]>
Cc: [email protected]
CWE ID: CWE-399
Target: 1
Example 2:
Code: void ScreenPositionController::ConvertPointToScreen(
const aura::Window* window,
gfx::Point* point) {
const aura::Window* root = window->GetRootWindow();
aura::Window::ConvertPointToTarget(window, root, point);
const gfx::Point display_origin = Shell::GetScreen()->GetDisplayNearestWindow(
const_cast<aura::Window*>(root)).bounds().origin();
point->Offset(display_origin.x(), display_origin.y());
}
Commit Message: Use the host coordinate when comparing to host window bounds.
I somehow overlooked this and the test was not strict enough to catch this.
BUG=521919
TEST=Updated ScreenPositionControllerTest.ConvertHostPointToScreenHiDPI so that it fails without the patch.
Review URL: https://codereview.chromium.org/1293373002
Cr-Commit-Position: refs/heads/master@{#344186}
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: read_response_body (struct http_stat *hs, int sock, FILE *fp, wgint contlen,
wgint contrange, bool chunked_transfer_encoding,
char *url, char *warc_timestamp_str, char *warc_request_uuid,
ip_address *warc_ip, char *type, int statcode, char *head)
{
int warc_payload_offset = 0;
FILE *warc_tmp = NULL;
int warcerr = 0;
int flags = 0;
if (opt.warc_filename != NULL)
{
/* Open a temporary file where we can write the response before we
add it to the WARC record. */
warc_tmp = warc_tempfile ();
if (warc_tmp == NULL)
warcerr = WARC_TMP_FOPENERR;
if (warcerr == 0)
{
/* We should keep the response headers for the WARC record. */
int head_len = strlen (head);
int warc_tmp_written = fwrite (head, 1, head_len, warc_tmp);
if (warc_tmp_written != head_len)
warcerr = WARC_TMP_FWRITEERR;
warc_payload_offset = head_len;
}
if (warcerr != 0)
{
if (warc_tmp != NULL)
fclose (warc_tmp);
return warcerr;
}
}
if (fp != NULL)
{
/* This confuses the timestamping code that checks for file size.
#### The timestamping code should be smarter about file size. */
if (opt.save_headers && hs->restval == 0)
fwrite (head, 1, strlen (head), fp);
}
/* Read the response body. */
if (contlen != -1)
/* If content-length is present, read that much; otherwise, read
until EOF. The HTTP spec doesn't require the server to
actually close the connection when it's done sending data. */
flags |= rb_read_exactly;
if (fp != NULL && hs->restval > 0 && contrange == 0)
/* If the server ignored our range request, instruct fd_read_body
to skip the first RESTVAL bytes of body. */
flags |= rb_skip_startpos;
if (chunked_transfer_encoding)
flags |= rb_chunked_transfer_encoding;
if (hs->remote_encoding == ENC_GZIP)
flags |= rb_compressed_gzip;
hs->len = hs->restval;
hs->rd_size = 0;
/* Download the response body and write it to fp.
If we are working on a WARC file, we simultaneously write the
response body to warc_tmp. */
hs->res = fd_read_body (hs->local_file, sock, fp, contlen != -1 ? contlen : 0,
hs->restval, &hs->rd_size, &hs->len, &hs->dltime,
flags, warc_tmp);
if (hs->res >= 0)
{
if (warc_tmp != NULL)
{
/* Create a response record and write it to the WARC file.
Note: per the WARC standard, the request and response should share
the same date header. We re-use the timestamp of the request.
The response record should also refer to the uuid of the request. */
bool r = warc_write_response_record (url, warc_timestamp_str,
warc_request_uuid, warc_ip,
warc_tmp, warc_payload_offset,
type, statcode, hs->newloc);
/* warc_write_response_record has closed warc_tmp. */
if (! r)
return WARC_ERR;
}
return RETRFINISHED;
}
if (warc_tmp != NULL)
fclose (warc_tmp);
if (hs->res == -2)
{
/* Error while writing to fd. */
return FWRITEERR;
}
else if (hs->res == -3)
{
/* Error while writing to warc_tmp. */
return WARC_TMP_FWRITEERR;
}
else
{
/* A read error! */
hs->rderrmsg = xstrdup (fd_errstr (sock));
return RETRFINISHED;
}
}
Commit Message:
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC)
{
zend_object_value new_obj_val;
zend_object *old_object;
zend_object *new_object;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
spl_filesystem_object *intern;
spl_filesystem_object *source;
int index, skip_dots;
old_object = zend_objects_get_address(zobject TSRMLS_CC);
source = (spl_filesystem_object*)old_object;
new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC);
new_object = &intern->std;
intern->flags = source->flags;
switch (source->type) {
case SPL_FS_INFO:
intern->_path_len = source->_path_len;
intern->_path = estrndup(source->_path, source->_path_len);
intern->file_name_len = source->file_name_len;
intern->file_name = estrndup(source->file_name, intern->file_name_len);
break;
case SPL_FS_DIR:
spl_filesystem_dir_open(intern, source->_path TSRMLS_CC);
/* read until we hit the position in which we were before */
skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS);
for(index = 0; index < source->u.dir.index; ++index) {
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
intern->u.dir.index = index;
break;
case SPL_FS_FILE:
php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name);
break;
}
intern->file_class = source->file_class;
intern->info_class = source->info_class;
intern->oth = source->oth;
intern->oth_handler = source->oth_handler;
zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC);
if (intern->oth_handler && intern->oth_handler->clone) {
intern->oth_handler->clone(source, intern TSRMLS_CC);
}
return new_obj_val;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: long Track::GetNumber() const { return m_info.number; }
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
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_error_handler (IceConn conn,
Bool swap,
int offending_minor_opcode,
unsigned long offending_sequence,
int error_class,
int severity,
IcePointer values)
{
g_debug ("GsmXsmpServer: ice_error_handler (%p, %s, %d, %lx, %d, %d)",
conn, swap ? "TRUE" : "FALSE", offending_minor_opcode,
offending_sequence, error_class, severity);
if (severity == IceCanContinue) {
return;
}
/* FIXME: the ICElib docs are completely vague about what we're
* supposed to do in this case. Need to verify that calling
* IceCloseConnection() here is guaranteed to cause neither
* free-memory-reads nor leaks.
*/
IceCloseConnection (conn);
}
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: static __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev,
struct rf_tech_specific_params_nfcf_poll *nfcf_poll,
__u8 *data)
{
nfcf_poll->bit_rate = *data++;
nfcf_poll->sensf_res_len = *data++;
pr_debug("bit_rate %d, sensf_res_len %d\n",
nfcf_poll->bit_rate, nfcf_poll->sensf_res_len);
memcpy(nfcf_poll->sensf_res, data, nfcf_poll->sensf_res_len);
data += nfcf_poll->sensf_res_len;
return data;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void crypto_xor_byte(u8 *a, const u8 *b, unsigned int size)
{
for (; size; size--)
*a++ ^= *b++;
}
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: xfs_icache_free_cowblocks(
struct xfs_mount *mp,
struct xfs_eofblocks *eofb)
{
return __xfs_icache_free_eofblocks(mp, eofb, xfs_inode_free_cowblocks,
XFS_ICI_COWBLOCKS_TAG);
}
Commit Message: xfs: validate cached inodes are free when allocated
A recent fuzzed filesystem image cached random dcache corruption
when the reproducer was run. This often showed up as panics in
lookup_slow() on a null inode->i_ops pointer when doing pathwalks.
BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
....
Call Trace:
lookup_slow+0x44/0x60
walk_component+0x3dd/0x9f0
link_path_walk+0x4a7/0x830
path_lookupat+0xc1/0x470
filename_lookup+0x129/0x270
user_path_at_empty+0x36/0x40
path_listxattr+0x98/0x110
SyS_listxattr+0x13/0x20
do_syscall_64+0xf5/0x280
entry_SYSCALL_64_after_hwframe+0x42/0xb7
but had many different failure modes including deadlocks trying to
lock the inode that was just allocated or KASAN reports of
use-after-free violations.
The cause of the problem was a corrupt INOBT on a v4 fs where the
root inode was marked as free in the inobt record. Hence when we
allocated an inode, it chose the root inode to allocate, found it in
the cache and re-initialised it.
We recently fixed a similar inode allocation issue caused by inobt
record corruption problem in xfs_iget_cache_miss() in commit
ee457001ed6c ("xfs: catch inode allocation state mismatch
corruption"). This change adds similar checks to the cache-hit path
to catch it, and turns the reproducer into a corruption shutdown
situation.
Reported-by: Wen Xu <[email protected]>
Signed-Off-By: Dave Chinner <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Carlos Maiolino <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
[darrick: fix typos in comment]
Signed-off-by: Darrick J. Wong <[email protected]>
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: parserep(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
u_int len;
enum sunrpc_accept_stat astat;
/*
* Portability note:
* Here we find the address of the ar_verf credentials.
* Originally, this calculation was
* dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf
* On the wire, the rp_acpt field starts immediately after
* the (32 bit) rp_stat field. However, rp_acpt (which is a
* "struct accepted_reply") contains a "struct opaque_auth",
* whose internal representation contains a pointer, so on a
* 64-bit machine the compiler inserts 32 bits of padding
* before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use
* the internal representation to parse the on-the-wire
* representation. Instead, we skip past the rp_stat field,
* which is an "enum" and so occupies one 32-bit word.
*/
dp = ((const uint32_t *)&rp->rm_reply) + 1;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len >= length)
return (NULL);
/*
* skip past the ar_verf credentials.
*/
dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);
ND_TCHECK2(dp[0], 0);
/*
* now we can check the ar_stat field
*/
astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);
if (astat != SUNRPC_SUCCESS) {
ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat)));
nfserr = 1; /* suppress trunc string */
return (NULL);
}
/* successful return */
ND_TCHECK2(*dp, sizeof(astat));
return ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));
trunc:
return (0);
}
Commit Message: CVE-2017-12898/NFS: Fix bounds checking.
Fix the bounds checking for the NFSv3 WRITE procedure to check whether the
length of the opaque data being written is present in the captured data,
not just whether the byte count is present in the captured data.
furthest forward in the packet, not the item before it. (This also lets
us eliminate the check for the "stable" argument being present in the
captured data; rewrite the code to print that to make it a bit clearer.)
Check that the entire ar_stat field is present in the capture.
Note that parse_wcc_attr() is called after we've already checked whether
the wcc_data is present.
Check before fetching the "access" part of the NFSv3 ACCESS results.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Include a test for the "check before fetching the "access" part..." fix,
using the capture supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: int jas_stream_read(jas_stream_t *stream, void *buf, int cnt)
{
int n;
int c;
char *bufptr;
JAS_DBGLOG(100, ("jas_stream_read(%p, %p, %d)\n", stream, buf, cnt));
if (cnt < 0) {
jas_deprecated("negative count for jas_stream_read");
}
bufptr = buf;
n = 0;
while (n < cnt) {
if ((c = jas_stream_getc(stream)) == EOF) {
return n;
}
*bufptr++ = c;
++n;
}
return n;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
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: flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436
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: tt_face_load_kern( TT_Face face,
FT_Stream stream )
{
FT_Error error;
FT_ULong table_size;
FT_Byte* p;
FT_Byte* p_limit;
FT_UInt nn, num_tables;
FT_UInt32 avail = 0, ordered = 0;
/* the kern table is optional; exit silently if it is missing */
error = face->goto_table( face, TTAG_kern, stream, &table_size );
if ( error )
goto Exit;
if ( table_size < 4 ) /* the case of a malformed table */
{
FT_ERROR(( "tt_face_load_kern:"
" kerning table is too small - ignored\n" ));
error = FT_THROW( Table_Missing );
goto Exit;
}
if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) )
{
FT_ERROR(( "tt_face_load_kern:"
" could not extract kerning table\n" ));
goto Exit;
}
face->kern_table_size = table_size;
p = face->kern_table;
p_limit = p + table_size;
p += 2; /* skip version */
num_tables = FT_NEXT_USHORT( p );
if ( num_tables > 32 ) /* we only support up to 32 sub-tables */
num_tables = 32;
for ( nn = 0; nn < num_tables; nn++ )
{
FT_UInt num_pairs, length, coverage;
FT_Byte* p_next;
FT_UInt32 mask = (FT_UInt32)1UL << nn;
if ( p + 6 > p_limit )
break;
p_next = p;
p += 2; /* skip version */
length = FT_NEXT_USHORT( p );
coverage = FT_NEXT_USHORT( p );
if ( length <= 6 )
break;
p_next += length;
if ( p_next > p_limit ) /* handle broken table */
p_next = p_limit;
/* only use horizontal kerning tables */
if ( ( coverage & ~8 ) != 0x0001 ||
p + 8 > p_limit )
goto NextTable;
num_pairs = FT_NEXT_USHORT( p );
p += 6;
if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */
num_pairs = (FT_UInt)( ( p_next - p ) / 6 );
avail |= mask;
/*
* Now check whether the pairs in this table are ordered.
* We then can use binary search.
*/
if ( num_pairs > 0 )
{
FT_ULong count;
FT_ULong old_pair;
old_pair = FT_NEXT_ULONG( p );
p += 2;
for ( count = num_pairs - 1; count > 0; count-- )
{
FT_UInt32 cur_pair;
cur_pair = FT_NEXT_ULONG( p );
if ( cur_pair <= old_pair )
break;
p += 2;
old_pair = cur_pair;
}
if ( count == 0 )
ordered |= mask;
}
NextTable:
p = p_next;
}
face->num_kern_tables = nn;
face->kern_avail_bits = avail;
face->kern_order_bits = ordered;
Exit:
return error;
}
Commit Message:
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
u32 *ptr_limit, u8 opcode, bool off_is_neg)
{
bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
(opcode == BPF_SUB && !off_is_neg);
u32 off;
switch (ptr_reg->type) {
case PTR_TO_STACK:
off = ptr_reg->off + ptr_reg->var_off.value;
if (mask_to_left)
*ptr_limit = MAX_BPF_STACK + off;
else
*ptr_limit = -off;
return 0;
case PTR_TO_MAP_VALUE:
if (mask_to_left) {
*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
} else {
off = ptr_reg->smin_value + ptr_reg->off;
*ptr_limit = ptr_reg->map_ptr->value_size - off;
}
return 0;
default:
return -EINVAL;
}
}
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Alexei Starovoitov <[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: SPL_METHOD(SplTempFileObject, __construct)
{
long max_memory = PHP_STREAM_MAX_MEM;
char tmp_fname[48];
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (max_memory < 0) {
intern->file_name = "php://memory";
intern->file_name_len = 12;
} else if (ZEND_NUM_ARGS()) {
intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory);
intern->file_name = tmp_fname;
} else {
intern->file_name = "php://temp";
intern->file_name_len = 10;
}
intern->u.file.open_mode = "wb";
intern->u.file.open_mode_len = 1;
intern->u.file.zcontext = NULL;
if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) {
intern->_path_len = 0;
intern->_path = estrndup("", 0);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::rewind()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
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 ppp_register_net_channel(struct net *net, struct ppp_channel *chan)
{
struct channel *pch;
struct ppp_net *pn;
pch = kzalloc(sizeof(struct channel), GFP_KERNEL);
if (!pch)
return -ENOMEM;
pn = ppp_pernet(net);
pch->ppp = NULL;
pch->chan = chan;
pch->chan_net = net;
chan->ppp = pch;
init_ppp_file(&pch->file, CHANNEL);
pch->file.hdrlen = chan->hdrlen;
#ifdef CONFIG_PPP_MULTILINK
pch->lastseq = -1;
#endif /* CONFIG_PPP_MULTILINK */
init_rwsem(&pch->chan_sem);
spin_lock_init(&pch->downl);
rwlock_init(&pch->upl);
spin_lock_bh(&pn->all_channels_lock);
pch->file.index = ++pn->last_channel_index;
list_add(&pch->list, &pn->new_channels);
atomic_inc(&channel_count);
spin_unlock_bh(&pn->all_channels_lock);
return 0;
}
Commit Message: ppp: take reference on channels netns
Let channels hold a reference on their network namespace.
Some channel types, like ppp_async and ppp_synctty, can have their
userspace controller running in a different namespace. Therefore they
can't rely on them to preclude their netns from being removed from
under them.
==================================================================
BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at
addr ffff880064e217e0
Read of size 8 by task syz-executor/11581
=============================================================================
BUG net_namespace (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906
[< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440
[< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469
[< inline >] slab_alloc_node kernel/mm/slub.c:2532
[< inline >] slab_alloc kernel/mm/slub.c:2574
[< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579
[< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597
[< inline >] net_alloc kernel/net/core/net_namespace.c:325
[< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360
[< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95
[< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150
[< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451
[< inline >] copy_process kernel/kernel/fork.c:1274
[< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723
[< inline >] SYSC_clone kernel/kernel/fork.c:1832
[< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826
[< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185
INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631
[< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650
[< inline >] slab_free kernel/mm/slub.c:2805
[< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814
[< inline >] net_free kernel/net/core/net_namespace.c:341
[< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348
[< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448
[< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036
[< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170
[< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303
[< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468
INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000
flags=0x5fffc0000004080
INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200
CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014
00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300
ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054
ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000
Call Trace:
[< inline >] __dump_stack kernel/lib/dump_stack.c:15
[<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50
[<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654
[<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661
[< inline >] print_address_description kernel/mm/kasan/report.c:138
[<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236
[< inline >] kasan_report kernel/mm/kasan/report.c:259
[<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280
[< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293
[<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241
[<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000
[<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478
[<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744
[<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772
[<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901
[<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688
[<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208
[<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244
[<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115
[< inline >] exit_task_work kernel/include/linux/task_work.h:21
[<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750
[<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123
[<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357
[<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550
[<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145
[<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880
[<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307
[< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113
[<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158
[<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712
[<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655
[<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165
[<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692
[< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099
[<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678
[< inline >] ? context_switch kernel/kernel/sched/core.c:2807
[<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283
[<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247
[< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282
[<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344
[<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281
Memory state around the buggy address:
ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2")
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Guillaume Nault <[email protected]>
Reviewed-by: Cyrill Gorcunov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: parsefsinfo(netdissect_options *ndo,
const uint32_t *dp)
{
const struct nfsv3_fsinfo *sfp;
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
if (er)
return (1);
sfp = (const struct nfsv3_fsinfo *)dp;
ND_TCHECK(*sfp);
ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u",
EXTRACT_32BITS(&sfp->fs_rtmax),
EXTRACT_32BITS(&sfp->fs_rtpref),
EXTRACT_32BITS(&sfp->fs_wtmax),
EXTRACT_32BITS(&sfp->fs_wtpref),
EXTRACT_32BITS(&sfp->fs_dtpref)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64,
EXTRACT_32BITS(&sfp->fs_rtmult),
EXTRACT_32BITS(&sfp->fs_wtmult),
EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize)));
ND_PRINT((ndo, " delta %u.%06u ",
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec),
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec)));
}
return (1);
trunc:
return (0);
}
Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data
This fixes a buffer over-read discovered by Kamil Frankowicz.
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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
ps_dec->process_called = 1;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
ps_dec->u4_stop_threads = 0;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base;
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
/* Since 8 bytes are read ahead, ensure 8 bytes are free at the
end of the buffer, which will be memset to 0 after emulation prevention */
buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8));
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
if(buflen >= MAX_NAL_UNIT_SIZE)
{
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
H264_DEC_DEBUG_PRINT(
"\nNal Size exceeded %d, Processing Stopped..\n",
MAX_NAL_UNIT_SIZE);
ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA;
ps_dec_op->e_pic_type = -1;
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/*signal end of frame decode for curren frame*/
if(ps_dec->u4_pic_buf_got == 0)
{
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded =
ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return IV_FAIL;
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
header_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
ps_dec->u4_slice_start_code_found = 0;
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
WORD32 ht_in_mbs;
ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag);
num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0))
prev_slice_err = 1;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) ||
(ret1 == ERROR_INV_SPS_PPS_T))
{
ret = ret1;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
&& (ps_dec->u4_pic_buf_got == 1))
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((0 == ps_dec->u4_num_reorder_frames_at_init)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
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
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: eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct eigrp_common_header *eigrp_com_header;
const struct eigrp_tlv_header *eigrp_tlv_header;
const u_char *tptr,*tlv_tptr;
u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length;
uint8_t prefix[4];
union {
const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm;
const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version;
const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int;
const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext;
const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup;
const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int;
const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext;
} tlv_ptr;
tptr=pptr;
eigrp_com_header = (const struct eigrp_common_header *)pptr;
ND_TCHECK(*eigrp_com_header);
/*
* Sanity checking of the header.
*/
if (eigrp_com_header->version != EIGRP_VERSION) {
ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "EIGRP %s, length: %u",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=len-sizeof(struct eigrp_common_header);
/* FIXME print other header info */
ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u",
eigrp_com_header->version,
tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode),
eigrp_com_header->opcode,
EXTRACT_16BITS(&eigrp_com_header->checksum),
tok2str(eigrp_common_header_flag_values,
"none",
EXTRACT_32BITS(&eigrp_com_header->flags)),
EXTRACT_32BITS(&eigrp_com_header->seq),
EXTRACT_32BITS(&eigrp_com_header->ack),
EXTRACT_32BITS(&eigrp_com_header->asn),
tlen));
tptr+=sizeof(const struct eigrp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header));
eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr;
eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length);
eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type);
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) ||
eigrp_tlv_len > tlen) {
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen);
return;
}
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u",
tok2str(eigrp_tlv_values,
"Unknown",
eigrp_tlv_type),
eigrp_tlv_type,
eigrp_tlv_len));
tlv_tptr=tptr+sizeof(struct eigrp_tlv_header);
tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, eigrp_tlv_len);
switch(eigrp_tlv_type) {
case EIGRP_TLV_GENERAL_PARM:
tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u",
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime),
tlv_ptr.eigrp_tlv_general_parm->k1,
tlv_ptr.eigrp_tlv_general_parm->k2,
tlv_ptr.eigrp_tlv_general_parm->k3,
tlv_ptr.eigrp_tlv_general_parm->k4,
tlv_ptr.eigrp_tlv_general_parm->k5));
break;
case EIGRP_TLV_SW_VERSION:
tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u",
tlv_ptr.eigrp_tlv_sw_version->ios_major,
tlv_ptr.eigrp_tlv_sw_version->ios_minor,
tlv_ptr.eigrp_tlv_sw_version->eigrp_major,
tlv_ptr.eigrp_tlv_sw_version->eigrp_minor));
break;
case EIGRP_TLV_IP_INT:
tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_int->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu),
tlv_ptr.eigrp_tlv_ip_int->hopcount,
tlv_ptr.eigrp_tlv_ip_int->reliability,
tlv_ptr.eigrp_tlv_ip_int->load));
break;
case EIGRP_TLV_IP_EXT:
tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr;
bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop)));
ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id),
tlv_ptr.eigrp_tlv_ip_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu),
tlv_ptr.eigrp_tlv_ip_ext->hopcount,
tlv_ptr.eigrp_tlv_ip_ext->reliability,
tlv_ptr.eigrp_tlv_ip_ext->load));
break;
case EIGRP_TLV_AT_CABLE_SETUP:
tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id)));
break;
case EIGRP_TLV_AT_INT:
tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2])));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu),
tlv_ptr.eigrp_tlv_at_int->hopcount,
tlv_ptr.eigrp_tlv_at_int->reliability,
tlv_ptr.eigrp_tlv_at_int->load));
break;
case EIGRP_TLV_AT_EXT:
tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2])));
ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id),
tlv_ptr.eigrp_tlv_at_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag),
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu),
tlv_ptr.eigrp_tlv_at_ext->hopcount,
tlv_ptr.eigrp_tlv_at_ext->reliability,
tlv_ptr.eigrp_tlv_at_ext->load));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case EIGRP_TLV_AUTH:
case EIGRP_TLV_SEQ:
case EIGRP_TLV_MCAST_SEQ:
case EIGRP_TLV_IPX_INT:
case EIGRP_TLV_IPX_EXT:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",
eigrp_tlv_len-sizeof(struct eigrp_tlv_header));
tptr+=eigrp_tlv_len;
tlen-=eigrp_tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
Commit Message: CVE-2017-12901/EIGRP: Do more length checks.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static __init int register_snapshot_cmd(void)
{
return register_ftrace_command(&ftrace_snapshot_cmd);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void InProcessBrowserTest::SetUp() {
DCHECK(!g_browser_process);
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kDisableOfflineAutoReload);
SetUpCommandLine(command_line);
PrepareTestCommandLine(command_line);
ASSERT_TRUE(CreateUserDataDirectory())
<< "Could not create user data directory.";
ASSERT_TRUE(SetUpUserDataDirectory())
<< "Could not set up user data directory.";
#if defined(OS_CHROMEOS)
base::FilePath log_dir = logging::GetSessionLogFile(*command_line).DirName();
base::CreateDirectory(log_dir);
#endif // defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
OSCrypt::UseMockKeychain(true);
#endif
#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
CaptivePortalService::set_state_for_testing(
CaptivePortalService::DISABLED_FOR_TESTING);
#endif
chrome_browser_net::NetErrorTabHelper::set_state_for_testing(
chrome_browser_net::NetErrorTabHelper::TESTING_FORCE_DISABLED);
google_util::SetMockLinkDoctorBaseURLForTesting();
#if defined(OS_WIN)
base::win::Version version = base::win::GetVersion();
if (version >= base::win::VERSION_VISTA &&
CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) {
com_initializer_.reset(new base::win::ScopedCOMInitializer());
ui::win::CreateATLModuleIfNeeded();
if (version >= base::win::VERSION_WIN8)
ASSERT_TRUE(win8::MakeTestDefaultBrowserSynchronously());
}
#endif
BrowserTestBase::SetUp();
}
Commit Message: Make the policy fetch for first time login blocking
The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users.
BUG=334584
Review URL: https://codereview.chromium.org/330843002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 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 _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
Target: 1
Example 2:
Code: static void NullableLongMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
base::Optional<int32_t> result = impl->nullableLongMethod();
if (!result)
V8SetReturnValueNull(info);
else
V8SetReturnValueInt(info, result.value());
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
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: struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
int noblock, int *err)
{
int peeked, off = 0;
return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, err);
}
Commit Message: net: fix infinite loop in __skb_recv_datagram()
Tommi was fuzzing with trinity and reported the following problem :
commit 3f518bf745 (datagram: Add offset argument to __skb_recv_datagram)
missed that a raw socket receive queue can contain skbs with no payload.
We can loop in __skb_recv_datagram() with MSG_PEEK mode, because
wait_for_packet() is not prepared to skip these skbs.
[ 83.541011] INFO: rcu_sched detected stalls on CPUs/tasks: {}
(detected by 0, t=26002 jiffies, g=27673, c=27672, q=75)
[ 83.541011] INFO: Stall ended before state dump start
[ 108.067010] BUG: soft lockup - CPU#0 stuck for 22s! [trinity-child31:2847]
...
[ 108.067010] Call Trace:
[ 108.067010] [<ffffffff818cc103>] __skb_recv_datagram+0x1a3/0x3b0
[ 108.067010] [<ffffffff818cc33d>] skb_recv_datagram+0x2d/0x30
[ 108.067010] [<ffffffff819ed43d>] rawv6_recvmsg+0xad/0x240
[ 108.067010] [<ffffffff818c4b04>] sock_common_recvmsg+0x34/0x50
[ 108.067010] [<ffffffff818bc8ec>] sock_recvmsg+0xbc/0xf0
[ 108.067010] [<ffffffff818bf31e>] sys_recvfrom+0xde/0x150
[ 108.067010] [<ffffffff81ca4329>] system_call_fastpath+0x16/0x1b
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Acked-by: Pavel Emelyanov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
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: TabContentsTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
old_browser_client_(NULL) {
}
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
Target: 1
Example 2:
Code: bool SystemClipboard::IsValidBufferType(mojom::ClipboardBuffer buffer) {
switch (buffer) {
case mojom::ClipboardBuffer::kStandard:
return true;
case mojom::ClipboardBuffer::kSelection:
#if defined(USE_X11)
return true;
#else
return false;
#endif
}
return true;
}
Commit Message: System Clipboard: Remove extraneous check for bitmap.getPixels()
Bug 369621 originally led to this check being introduced via
https://codereview.chromium.org/289573002/patch/40001/50002, but after
https://crrev.com/c/1345809, I'm not sure that it's still necessary.
This change succeeds when tested against the "minimized test case" provided in
crbug.com/369621 's description, but I'm unsure how to make the minimized test
case fail, so this doesn't prove that the change would succeed against the
fuzzer's test case (which originally filed the bug).
As I'm unable to view the relevant fuzzer test case, (see crbug.com/918705),
I don't know exactly what may have caused the fuzzer to fail. Therefore,
I've added a CHECK for the time being, so that we will be notified in canary
if my assumption was incorrect.
Bug: 369621
Change-Id: Ie9b47a4b38ba1ed47624de776015728e541d27f7
Reviewed-on: https://chromium-review.googlesource.com/c/1393436
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#619591}
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 PlatformSensorProviderBase::RemoveSensor(mojom::SensorType type,
PlatformSensor* sensor) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto it = sensor_map_.find(type);
if (it == sensor_map_.end()) {
return;
}
if (sensor != it->second) {
NOTREACHED()
<< "not expecting to track more than one sensor of the same type";
return;
}
sensor_map_.erase(type);
FreeResourcesIfNeeded();
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732
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 Element* siblingWithAriaRole(String role, Node* node) {
Node* parent = node->parentNode();
if (!parent)
return 0;
for (Element* sibling = ElementTraversal::firstChild(*parent); sibling;
sibling = ElementTraversal::nextSibling(*sibling)) {
const AtomicString& siblingAriaRole =
AccessibleNode::getProperty(sibling, AOMStringProperty::kRole);
if (equalIgnoringCase(siblingAriaRole, role))
return sibling;
}
return 0;
}
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: void ipc_rcu_free(struct rcu_head *head)
{
struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
kvfree(p);
}
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
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 nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = openflags;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, openflags);
*res = newstate;
return 0;
}
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: static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
{
return rq_clock_task(rq_of(cfs_rq));
}
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bitmap_paint(gs_image_enum * pen, gs_data_image_t * pim,
const gs_depth_bitmap * pbitmap, gs_gstate * pgs)
{
uint raster = pbitmap->raster;
uint nbytes = (pim->Width * pbitmap->pix_depth + 7) >> 3;
uint used;
const byte *dp = pbitmap->data;
int n;
int code = 0, code1;
if (nbytes == raster)
code = gs_image_next(pen, dp, nbytes * pim->Height, &used);
else
for (n = pim->Height; n > 0 && code >= 0; dp += raster, --n)
code = gs_image_next(pen, dp, nbytes, &used);
code1 = gs_image_cleanup_and_free_enum(pen, pgs);
if (code >= 0 && code1 < 0)
code = code1;
return code;
}
Commit Message:
CWE ID: CWE-704
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: append_quoted (struct stringbuf *sb, const unsigned char *value, size_t length,
int skip)
{
unsigned char tmp[4];
const unsigned char *s = value;
size_t n = 0;
for (;;)
{
for (value = s; n+skip < length; n++, s++)
{
s += skip;
n += skip;
if (*s < ' ' || *s > 126 || strchr (",+\"\\<>;", *s) )
break;
}
if (s != value)
put_stringbuf_mem_skip (sb, value, s-value, skip);
if (n+skip >= length)
return; /* ready */
s += skip;
n += skip;
if ( *s < ' ' || *s > 126 )
{
sprintf (tmp, "\\%02X", *s);
put_stringbuf_mem (sb, tmp, 3);
}
else
{
tmp[0] = '\\';
tmp[1] = *s;
put_stringbuf_mem (sb, tmp, 2);
}
n++; s++;
}
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AutocompleteEditModel::FinalizeInstantQuery(
const string16& input_text,
const string16& suggest_text,
bool skip_inline_autocomplete) {
if (skip_inline_autocomplete) {
const string16 final_text = input_text + suggest_text;
view_->OnBeforePossibleChange();
view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
false);
view_->OnAfterPossibleChange();
} else if (popup_->IsOpen()) {
SearchProvider* search_provider =
autocomplete_controller_->search_provider();
if (search_provider)
search_provider->FinalizeInstantQuery(input_text, suggest_text);
}
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 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: int ff_h263_decode_picture_header(MpegEncContext *s)
{
int format, width, height, i;
uint32_t startcode;
align_get_bits(&s->gb);
startcode= get_bits(&s->gb, 22-8);
for(i= get_bits_left(&s->gb); i>24; i-=8) {
startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;
if(startcode == 0x20)
break;
}
if (startcode != 0x20) {
av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
return -1;
}
/* temporal reference */
i = get_bits(&s->gb, 8); /* picture timestamp */
if( (s->picture_number&~0xFF)+i < s->picture_number)
i+= 256;
s->picture_number= (s->picture_number&~0xFF) + i;
/* PTYPE starts here */
if (get_bits1(&s->gb) != 1) {
/* marker */
av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n");
return -1;
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n");
return -1; /* h263 id */
}
skip_bits1(&s->gb); /* split screen off */
skip_bits1(&s->gb); /* camera off */
skip_bits1(&s->gb); /* freeze picture release off */
format = get_bits(&s->gb, 3);
/*
0 forbidden
1 sub-QCIF
10 QCIF
7 extended PTYPE (PLUSPTYPE)
*/
if (format != 7 && format != 6) {
s->h263_plus = 0;
/* H.263v1 */
/* H.263v1 */
width = ff_h263_format[format][0];
height = ff_h263_format[format][1];
if (!width)
return -1;
s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb);
s->h263_long_vectors = get_bits1(&s->gb);
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n");
return -1; /* SAC: off */
}
s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */
s->unrestricted_mv = s->h263_long_vectors || s->obmc;
s->pb_frame = get_bits1(&s->gb);
s->chroma_qscale= s->qscale = get_bits(&s->gb, 5);
skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */
s->width = width;
s->height = height;
s->avctx->sample_aspect_ratio= (AVRational){12,11};
s->avctx->framerate = (AVRational){ 30000, 1001 };
} else {
int ufep;
/* H.263v2 */
s->h263_plus = 1;
ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
/* ufep other than 0 and 1 are reserved */
if (ufep == 1) {
/* OPPTYPE */
format = get_bits(&s->gb, 3);
ff_dlog(s->avctx, "ufep=1, format: %d\n", format);
s->custom_pcf= get_bits1(&s->gb);
s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n");
}
s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */
s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */
s->loop_filter= get_bits1(&s->gb);
s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter;
s->h263_slice_structured= get_bits1(&s->gb);
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n");
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n");
}
s->alt_inter_vlc= get_bits1(&s->gb);
s->modified_quant= get_bits1(&s->gb);
if(s->modified_quant)
s->chroma_qscale_table= ff_h263_chroma_qscale_table;
skip_bits(&s->gb, 1); /* Prevent start code emulation */
skip_bits(&s->gb, 3); /* Reserved */
} else if (ufep != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep);
return -1;
}
/* MPPTYPE */
s->pict_type = get_bits(&s->gb, 3);
switch(s->pict_type){
case 0: s->pict_type= AV_PICTURE_TYPE_I;break;
case 1: s->pict_type= AV_PICTURE_TYPE_P;break;
case 2: s->pict_type= AV_PICTURE_TYPE_P;s->pb_frame = 3;break;
case 3: s->pict_type= AV_PICTURE_TYPE_B;break;
case 7: s->pict_type= AV_PICTURE_TYPE_I;break; //ZYGO
default:
return -1;
}
skip_bits(&s->gb, 2);
s->no_rounding = get_bits1(&s->gb);
skip_bits(&s->gb, 4);
/* Get the picture dimensions */
if (ufep) {
if (format == 6) {
/* Custom Picture Format (CPFMT) */
s->aspect_ratio_info = get_bits(&s->gb, 4);
ff_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info);
/* aspect ratios:
0 - forbidden
1 - 1:1
2 - 12:11 (CIF 4:3)
3 - 10:11 (525-type 4:3)
4 - 16:11 (CIF 16:9)
5 - 40:33 (525-type 16:9)
6-14 - reserved
*/
width = (get_bits(&s->gb, 9) + 1) * 4;
skip_bits1(&s->gb);
height = get_bits(&s->gb, 9) * 4;
ff_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
/* aspected dimensions */
s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8);
s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8);
}else{
s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
}
} else {
width = ff_h263_format[format][0];
height = ff_h263_format[format][1];
s->avctx->sample_aspect_ratio= (AVRational){12,11};
}
if ((width == 0) || (height == 0))
return -1;
s->width = width;
s->height = height;
if(s->custom_pcf){
int gcd;
s->avctx->framerate.num = 1800000;
s->avctx->framerate.den = 1000 + get_bits1(&s->gb);
s->avctx->framerate.den *= get_bits(&s->gb, 7);
if(s->avctx->framerate.den == 0){
av_log(s, AV_LOG_ERROR, "zero framerate\n");
return -1;
}
gcd= av_gcd(s->avctx->framerate.den, s->avctx->framerate.num);
s->avctx->framerate.den /= gcd;
s->avctx->framerate.num /= gcd;
}else{
s->avctx->framerate = (AVRational){ 30000, 1001 };
}
}
if(s->custom_pcf){
skip_bits(&s->gb, 2); //extended Temporal reference
}
if (ufep) {
if (s->umvplus) {
if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
skip_bits1(&s->gb);
}
if(s->h263_slice_structured){
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n");
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n");
}
}
}
s->qscale = get_bits(&s->gb, 5);
}
s->mb_width = (s->width + 15) / 16;
s->mb_height = (s->height + 15) / 16;
s->mb_num = s->mb_width * s->mb_height;
skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */
if (s->custom_pcf)
skip_bits(&s->gb, 2); //extended Temporal reference
skip_bits(&s->gb, 2); /* Quantization information for B-pictures */
}
Commit Message:
CWE ID: CWE-189
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 edge_bulk_in_callback(struct urb *urb)
{
struct edgeport_port *edge_port = urb->context;
struct device *dev = &edge_port->port->dev;
unsigned char *data = urb->transfer_buffer;
int retval = 0;
int port_number;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status);
}
if (status == -EPIPE)
goto exit;
if (status) {
dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__);
return;
}
port_number = edge_port->port->port_number;
if (edge_port->lsr_event) {
edge_port->lsr_event = 0;
dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n",
__func__, port_number, edge_port->lsr_mask, *data);
handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);
/* Adjust buffer length/pointer */
--urb->actual_length;
++data;
}
if (urb->actual_length) {
usb_serial_debug_data(dev, __func__, urb->actual_length, data);
if (edge_port->close_pending)
dev_dbg(dev, "%s - close pending, dropping data on the floor\n",
__func__);
else
edge_tty_recv(edge_port->port, data,
urb->actual_length);
edge_port->port->icount.rx += urb->actual_length;
}
exit:
/* continue read unless stopped */
spin_lock(&edge_port->ep_lock);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)
retval = usb_submit_urb(urb, GFP_ATOMIC);
else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING)
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;
spin_unlock(&edge_port->ep_lock);
if (retval)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval);
}
Commit Message: USB: serial: io_ti: fix information leak in completion handler
Add missing sanity check to the bulk-in completion handler to avoid an
integer underflow that can be triggered by a malicious device.
This avoids leaking 128 kB of memory content from after the URB transfer
buffer to user space.
Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32")
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]> # 2.6.30
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-191
Target: 1
Example 2:
Code: static struct in_device *inetdev_init(struct net_device *dev)
{
struct in_device *in_dev;
int err = -ENOMEM;
ASSERT_RTNL();
in_dev = kzalloc(sizeof(*in_dev), GFP_KERNEL);
if (!in_dev)
goto out;
memcpy(&in_dev->cnf, dev_net(dev)->ipv4.devconf_dflt,
sizeof(in_dev->cnf));
in_dev->cnf.sysctl = NULL;
in_dev->dev = dev;
in_dev->arp_parms = neigh_parms_alloc(dev, &arp_tbl);
if (!in_dev->arp_parms)
goto out_kfree;
if (IPV4_DEVCONF(in_dev->cnf, FORWARDING))
dev_disable_lro(dev);
/* Reference in_dev->dev */
dev_hold(dev);
/* Account for reference dev->ip_ptr (below) */
in_dev_hold(in_dev);
err = devinet_sysctl_register(in_dev);
if (err) {
in_dev->dead = 1;
in_dev_put(in_dev);
in_dev = NULL;
goto out;
}
ip_mc_init_dev(in_dev);
if (dev->flags & IFF_UP)
ip_mc_up(in_dev);
/* we can receive as soon as ip_ptr is set -- do this last */
rcu_assign_pointer(dev->ip_ptr, in_dev);
out:
return in_dev ?: ERR_PTR(err);
out_kfree:
kfree(in_dev);
in_dev = NULL;
goto out;
}
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: 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 posix_cpu_nsleep_restart(struct restart_block *restart_block)
{
clockid_t which_clock = restart_block->arg0;
struct timespec __user *rmtp;
struct timespec t;
struct itimerspec it;
int error;
rmtp = (struct timespec __user *) restart_block->arg1;
t.tv_sec = restart_block->arg2;
t.tv_nsec = restart_block->arg3;
restart_block->fn = do_no_restart_syscall;
error = do_cpu_nanosleep(which_clock, TIMER_ABSTIME, &t, &it);
if (error == -ERESTART_RESTARTBLOCK) {
/*
* Report back to the user the time still remaining.
*/
if (rmtp != NULL && copy_to_user(rmtp, &it.it_value, sizeof *rmtp))
return -EFAULT;
restart_block->fn = posix_cpu_nsleep_restart;
restart_block->arg0 = which_clock;
restart_block->arg1 = (unsigned long) rmtp;
restart_block->arg2 = t.tv_sec;
restart_block->arg3 = t.tv_nsec;
}
return error;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
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: WebRunnerMainDelegate::WebRunnerMainDelegate(zx::channel context_channel)
: context_channel_(std::move(context_channel)) {}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264
Target: 1
Example 2:
Code: gsm_xsmp_server_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsmXsmpServer *self;
self = GSM_XSMP_SERVER (object);
switch (prop_id) {
case PROP_CLIENT_STORE:
gsm_xsmp_server_set_client_store (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
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
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 vrend_renderer_context_destroy(uint32_t handle)
{
struct vrend_decode_ctx *ctx;
bool ret;
if (handle >= VREND_MAX_CTX)
return;
ctx = dec_ctx[handle];
if (!ctx)
return;
vrend_hw_switch_context(dec_ctx[0]->grctx, true);
}
Commit Message:
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void GLES2Implementation::GetProgramResourceiv(GLuint program,
GLenum program_interface,
GLuint index,
GLsizei prop_count,
const GLenum* props,
GLsizei bufsize,
GLsizei* length,
GLint* params) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glGetProgramResourceiv(" << program
<< ", " << program_interface << ", " << index << ", "
<< prop_count << ", " << static_cast<const void*>(props)
<< ", " << bufsize << ", " << static_cast<void*>(length)
<< ", " << static_cast<void*>(params) << ")");
if (prop_count < 0) {
SetGLError(GL_INVALID_VALUE, "glGetProgramResourceiv", "prop_count < 0");
return;
}
if (bufsize < 0) {
SetGLError(GL_INVALID_VALUE, "glGetProgramResourceiv", "bufsize < 0");
return;
}
TRACE_EVENT0("gpu", "GLES2::GetProgramResourceiv");
GLsizei param_count = 0;
bool success = share_group_->program_info_manager()->GetProgramResourceiv(
this, program, program_interface, index, prop_count, props, bufsize,
¶m_count, params);
if (length) {
*length = param_count;
}
if (success && params) {
GPU_CLIENT_LOG_CODE_BLOCK({
for (GLsizei ii = 0; ii < param_count; ++ii) {
GPU_CLIENT_LOG(" " << ii << ": " << params[ii]);
}
});
}
CheckGLError();
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
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 ExecuteMoveToRightEndOfLineAndModifySelection(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
frame.Selection().Modify(
SelectionModifyAlteration::kExtend, SelectionModifyDirection::kRight,
TextGranularity::kLineBoundary, SetSelectionBy::kUser);
return true;
}
Commit Message: Move Editor::Transpose() out of Editor class
This patch moves |Editor::Transpose()| out of |Editor| class as preparation of
expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor|
class simpler for improving code health.
Following patch will expand |Transpose()| into |ExecutTranspose()|.
Bug: 672405
Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6
Reviewed-on: https://chromium-review.googlesource.com/583880
Reviewed-by: Xiaocheng Hu <[email protected]>
Commit-Queue: Yoshifumi Inoue <[email protected]>
Cr-Commit-Position: refs/heads/master@{#489518}
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: AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringCase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringCase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringCase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringCase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringCase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringCase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
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: ChromeContentBrowserClientExtensionsPart::GetVpnServiceProxy(
content::BrowserContext* browser_context) {
#if defined(OS_CHROMEOS)
chromeos::VpnService* vpn_service =
chromeos::VpnServiceFactory::GetForBrowserContext(browser_context);
if (!vpn_service)
return nullptr;
return vpn_service->GetVpnServiceProxy();
#else
return nullptr;
#endif
}
Commit Message: [Extensions] Update navigations across hypothetical extension extents
Update code to treat navigations across hypothetical extension extents
(e.g. for nonexistent extensions) the same as we do for navigations
crossing installed extension extents.
Bug: 598265
Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b
Reviewed-on: https://chromium-review.googlesource.com/617180
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#495779}
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 sched_destroy_group(struct task_group *tg)
{
/* wait for possible concurrent references to cfs_rqs complete */
call_rcu(&tg->rcu, sched_free_group_rcu);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const {
return original_context_.get();
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: nfsd4_lookup_stateid(struct nfsd4_compound_state *cstate,
stateid_t *stateid, unsigned char typemask,
struct nfs4_stid **s, struct nfsd_net *nn)
{
__be32 status;
if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
return nfserr_bad_stateid;
status = lookup_clientid(&stateid->si_opaque.so_clid, cstate, nn);
if (status == nfserr_stale_clientid) {
if (cstate->session)
return nfserr_bad_stateid;
return nfserr_stale_stateid;
}
if (status)
return status;
*s = find_stateid_by_type(cstate->clp, stateid, typemask);
if (!*s)
return nfserr_bad_stateid;
return nfs_ok;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ACodec::LoadedState::onStart() {
ALOGV("onStart");
status_t err = mCodec->mOMX->sendCommand(mCodec->mNode, OMX_CommandStateSet, OMX_StateIdle);
if (err != OK) {
mCodec->signalError(OMX_ErrorUndefined, makeNoSideEffectStatus(err));
} else {
mCodec->changeState(mCodec->mLoadedToIdleState);
}
}
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 v8::Handle<v8::Value> intMethodWithArgsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.intMethodWithArgs");
if (args.Length() < 3)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0);
return v8::Integer::New(imp->intMethodWithArgs(intArg, strArg, objArg));
}
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: void red_channel_client_pipe_add_after(RedChannelClient *rcc,
PipeItem *item, PipeItem *pos)
{
spice_assert(rcc);
spice_assert(pos);
spice_assert(item);
rcc->pipe_size++;
ring_add_after(&item->link, &pos->link);
}
Commit Message:
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostImpl::SendInputEvent(const WebInputEvent& input_event,
int event_size,
bool is_keyboard_shortcut) {
IPC::Message* message = new ViewMsg_HandleInputEvent(routing_id_);
message->WriteData(
reinterpret_cast<const char*>(&input_event), event_size);
if (input_event.type == WebInputEvent::RawKeyDown)
message->WriteBool(is_keyboard_shortcut);
input_event_start_time_ = TimeTicks::Now();
Send(message);
increment_in_flight_event_count();
}
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: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Tracks::ParseTrackEntry(
long long track_start,
long long track_size,
long long element_start,
long long element_size,
Track*& pResult) const
{
if (pResult)
return -1;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = track_start;
const long long track_stop = track_start + track_size;
Track::Info info;
info.type = 0;
info.number = 0;
info.uid = 0;
info.defaultDuration = 0;
Track::Settings v;
v.start = -1;
v.size = -1;
Track::Settings a;
a.start = -1;
a.size = -1;
Track::Settings e; //content_encodings_settings;
e.start = -1;
e.size = -1;
long long lacing = 1; //default is true
while (pos < track_stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
track_stop,
id,
size);
if (status < 0) //error
return status;
if (size < 0)
return E_FILE_FORMAT_INVALID;
const long long start = pos;
if (id == 0x60) // VideoSettings ID
{
v.start = start;
v.size = size;
}
else if (id == 0x61) // AudioSettings ID
{
a.start = start;
a.size = size;
}
else if (id == 0x2D80) // ContentEncodings ID
{
e.start = start;
e.size = size;
}
else if (id == 0x33C5) //Track UID
{
if (size > 8)
return E_FILE_FORMAT_INVALID;
info.uid = 0;
long long pos_ = start;
const long long pos_end = start + size;
while (pos_ != pos_end)
{
unsigned char b;
const int status = pReader->Read(pos_, 1, &b);
if (status)
return status;
info.uid <<= 8;
info.uid |= b;
++pos_;
}
}
else if (id == 0x57) //Track Number
{
const long long num = UnserializeUInt(pReader, pos, size);
if ((num <= 0) || (num > 127))
return E_FILE_FORMAT_INVALID;
info.number = static_cast<long>(num);
}
else if (id == 0x03) //Track Type
{
const long long type = UnserializeUInt(pReader, pos, size);
if ((type <= 0) || (type > 254))
return E_FILE_FORMAT_INVALID;
info.type = static_cast<long>(type);
}
else if (id == 0x136E) //Track Name
{
const long status = UnserializeString(
pReader,
pos,
size,
info.nameAsUTF8);
if (status)
return status;
}
else if (id == 0x02B59C) //Track Language
{
const long status = UnserializeString(
pReader,
pos,
size,
info.language);
if (status)
return status;
}
else if (id == 0x03E383) //Default Duration
{
const long long duration = UnserializeUInt(pReader, pos, size);
if (duration < 0)
return E_FILE_FORMAT_INVALID;
info.defaultDuration = static_cast<unsigned long long>(duration);
}
else if (id == 0x06) //CodecID
{
const long status = UnserializeString(
pReader,
pos,
size,
info.codecId);
if (status)
return status;
}
else if (id == 0x1C) //lacing
{
lacing = UnserializeUInt(pReader, pos, size);
if ((lacing < 0) || (lacing > 1))
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x23A2) //Codec Private
{
delete[] info.codecPrivate;
info.codecPrivate = NULL;
info.codecPrivateSize = 0;
const size_t buflen = static_cast<size_t>(size);
if (buflen)
{
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int status = pReader->Read(pos, buflen, buf);
if (status)
{
delete[] buf;
return status;
}
info.codecPrivate = buf;
info.codecPrivateSize = buflen;
}
}
else if (id == 0x058688) //Codec Name
{
const long status = UnserializeString(
pReader,
pos,
size,
info.codecNameAsUTF8);
if (status)
return status;
}
else if (id == 0x16AA) //Codec Delay
{
info.codecDelay = UnserializeUInt(pReader, pos, size);
}
else if (id == 0x16BB) //Seek Pre Roll
{
info.seekPreRoll = UnserializeUInt(pReader, pos, size);
}
pos += size; //consume payload
assert(pos <= track_stop);
}
assert(pos == track_stop);
if (info.number <= 0) //not specified
return E_FILE_FORMAT_INVALID;
if (GetTrackByNumber(info.number))
return E_FILE_FORMAT_INVALID;
if (info.type <= 0) //not specified
return E_FILE_FORMAT_INVALID;
info.lacing = (lacing > 0) ? true : false;
if (info.type == Track::kVideo)
{
if (v.start < 0)
return E_FILE_FORMAT_INVALID;
if (a.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings = v;
VideoTrack* pTrack = NULL;
const long status = VideoTrack::Parse(m_pSegment,
info,
element_start,
element_size,
pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
if (e.start >= 0)
pResult->ParseContentEncodingsEntry(e.start, e.size);
}
else if (info.type == Track::kAudio)
{
if (a.start < 0)
return E_FILE_FORMAT_INVALID;
if (v.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings = a;
AudioTrack* pTrack = NULL;
const long status = AudioTrack::Parse(m_pSegment,
info,
element_start,
element_size,
pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
if (e.start >= 0)
pResult->ParseContentEncodingsEntry(e.start, e.size);
}
else
{
if (a.start >= 0)
return E_FILE_FORMAT_INVALID;
if (v.start >= 0)
return E_FILE_FORMAT_INVALID;
if (e.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings.start = -1;
info.settings.size = 0;
Track* pTrack = NULL;
const long status = Track::Create(m_pSegment,
info,
element_start,
element_size,
pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
}
return 0; //success
}
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: static int init(bt_callbacks_t *callbacks) {
LOG_INFO("%s", __func__);
if (interface_ready())
return BT_STATUS_DONE;
#ifdef BLUEDROID_DEBUG
allocation_tracker_init();
#endif
bt_hal_cbacks = callbacks;
stack_manager_get_interface()->init_stack();
btif_debug_init();
return BT_STATUS_SUCCESS;
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
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 megasas_frame_set_scsi_status(MegasasState *s,
unsigned long frame, uint8_t v)
{
PCIDevice *pci = &s->parent_obj;
stb_pci_dma(pci, frame + offsetof(struct mfi_frame_header, scsi_status), v);
}
Commit Message:
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: static int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
Commit Message: isofs: Fix infinite looping over CE entries
Rock Ridge extensions define so called Continuation Entries (CE) which
define where is further space with Rock Ridge data. Corrupted isofs
image can contain arbitrarily long chain of these, including a one
containing loop and thus causing kernel to end in an infinite loop when
traversing these entries.
Limit the traversal to 32 entries which should be more than enough space
to store all the Rock Ridge data.
Reported-by: P J P <[email protected]>
CC: [email protected]
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int pci_cirrus_vga_initfn(PCIDevice *dev)
{
PCICirrusVGAState *d = DO_UPCAST(PCICirrusVGAState, dev, dev);
CirrusVGAState *s = &d->cirrus_vga;
PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
int16_t device_id = pc->device_id;
/* follow real hardware, cirrus card emulated has 4 MB video memory.
Also accept 8 MB/16 MB for backward compatibility. */
if (s->vga.vram_size_mb != 4 && s->vga.vram_size_mb != 8 &&
s->vga.vram_size_mb != 16) {
error_report("Invalid cirrus_vga ram size '%u'",
s->vga.vram_size_mb);
return -1;
}
/* setup VGA */
vga_common_init(&s->vga, OBJECT(dev), true);
cirrus_init_common(s, OBJECT(dev), device_id, 1, pci_address_space(dev),
pci_address_space_io(dev));
s->vga.con = graphic_console_init(DEVICE(dev), 0, s->vga.hw_ops, &s->vga);
/* setup PCI */
memory_region_init(&s->pci_bar, OBJECT(dev), "cirrus-pci-bar0", 0x2000000);
/* XXX: add byte swapping apertures */
memory_region_add_subregion(&s->pci_bar, 0, &s->cirrus_linear_io);
memory_region_add_subregion(&s->pci_bar, 0x1000000,
&s->cirrus_linear_bitblt_io);
/* setup memory space */
/* memory #0 LFB */
/* memory #1 memory-mapped I/O */
/* XXX: s->vga.vram_size must be a power of two */
pci_register_bar(&d->dev, 0, PCI_BASE_ADDRESS_MEM_PREFETCH, &s->pci_bar);
if (device_id == CIRRUS_ID_CLGD5446) {
pci_register_bar(&d->dev, 1, 0, &s->cirrus_mmio_io);
}
return 0;
}
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: logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask)
{
char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4;
char *mask_decoded5;
const char *dir_separator;
int length;
time_t seconds;
struct tm *date_tmp;
mask2 = NULL;
mask_decoded = NULL;
mask_decoded2 = NULL;
mask_decoded3 = NULL;
mask_decoded4 = NULL;
mask_decoded5 = NULL;
dir_separator = weechat_info_get ("dir_separator", "");
if (!dir_separator)
return NULL;
/*
* we first replace directory separator (commonly '/') by \01 because
* buffer mask can contain this char, and will be replaced by replacement
* char ('_' by default)
*/
mask2 = weechat_string_replace (mask, dir_separator, "\01");
if (!mask2)
goto end;
mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2);
if (!mask_decoded)
goto end;
mask_decoded2 = weechat_string_replace (mask_decoded,
dir_separator,
weechat_config_string (logger_config_file_replacement_char));
if (!mask_decoded2)
goto end;
#ifdef __CYGWIN__
mask_decoded3 = weechat_string_replace (mask_decoded2, "\\",
weechat_config_string (logger_config_file_replacement_char));
#else
mask_decoded3 = strdup (mask_decoded2);
#endif /* __CYGWIN__ */
if (!mask_decoded3)
goto end;
/* restore directory separator */
mask_decoded4 = weechat_string_replace (mask_decoded3,
"\01", dir_separator);
if (!mask_decoded4)
goto end;
/* replace date/time specifiers in mask */
length = strlen (mask_decoded4) + 256 + 1;
mask_decoded5 = malloc (length);
if (!mask_decoded5)
goto end;
seconds = time (NULL);
date_tmp = localtime (&seconds);
mask_decoded5[0] = '\0';
strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp);
/* convert to lower case? */
if (weechat_config_boolean (logger_config_file_name_lower_case))
weechat_string_tolower (mask_decoded5);
if (weechat_logger_plugin->debug)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: buffer = \"%s\", mask = \"%s\", "
"decoded mask = \"%s\"",
LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (buffer, "name"),
mask, mask_decoded5);
}
end:
if (mask2)
free (mask2);
if (mask_decoded)
free (mask_decoded);
if (mask_decoded2)
free (mask_decoded2);
if (mask_decoded3)
free (mask_decoded3);
if (mask_decoded4)
free (mask_decoded4);
return mask_decoded5;
}
Commit Message: logger: call strftime before replacing buffer local variables
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *sockaddr_url, *stratum_port, *tmp;
char *url, *port, address[256];
if (opt_disable_client_reconnect) {
applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting.");
return false;
}
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
sprintf(address, "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
Commit Message: stratum: parse_reconnect(): treat pool-sent URL as untrusted.
Thanks to Mick Ayzenberg <[email protected]> for reminding
that this existed and highlighting the offender.
Also to Luke-jr for actually fixing this in bfgminer. :D
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void _gdScaleRow(gdImagePtr pSrc, unsigned int src_width, gdImagePtr dst, unsigned int dst_width, unsigned int row, LineContribType *contrib)
{
int *p_src_row = pSrc->tpixels[row];
int *p_dst_row = dst->tpixels[row];
unsigned int x;
for (x = 0; x < dst_width - 1; x++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int left = contrib->ContribRow[x].Left;
const int right = contrib->ContribRow[x].Right;
int i;
/* Accumulate each channel */
for (i = left; i <= right; i++) {
const int left_channel = i - left;
r += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetRed(p_src_row[i])));
g += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetGreen(p_src_row[i])));
b += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetBlue(p_src_row[i])));
a += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetAlpha(p_src_row[i])));
}
p_dst_row[x] = gdTrueColorAlpha(r, g, b, a);
}
}
Commit Message: Fixed memory overrun bug in gdImageScaleTwoPass
_gdContributionsCalc would compute a window size and then adjust
the left and right positions of the window to make a window within
that size. However, it was storing the values in the struct *before*
it made the adjustment. This change fixes that.
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: PHP_FUNCTION(pg_end_copy)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
int result = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQendcopy(pgsql);
if (result!=0) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
Commit Message:
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ShellBrowserMain(const content::MainFunctionParams& parameters) {
bool layout_test_mode =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);
base::ScopedTempDir browser_context_path_for_layout_tests;
if (layout_test_mode) {
CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());
CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kContentShellDataPath,
browser_context_path_for_layout_tests.path().MaybeAsASCII());
}
scoped_ptr<content::BrowserMainRunner> main_runner_(
content::BrowserMainRunner::Create());
int exit_code = main_runner_->Initialize(parameters);
if (exit_code >= 0)
return exit_code;
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kCheckLayoutTestSysDeps)) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
main_runner_->Shutdown();
return 0;
}
if (layout_test_mode) {
content::WebKitTestController test_controller;
std::string test_string;
CommandLine::StringVector args =
CommandLine::ForCurrentProcess()->GetArgs();
size_t command_line_position = 0;
bool ran_at_least_once = false;
#if defined(OS_ANDROID)
std::cout << "#READY\n";
std::cout.flush();
#endif
while (GetNextTest(args, &command_line_position, &test_string)) {
if (test_string.empty())
continue;
if (test_string == "QUIT")
break;
bool enable_pixel_dumps;
std::string pixel_hash;
FilePath cwd;
GURL test_url = GetURLForLayoutTest(
test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
test_url, cwd, enable_pixel_dumps, pixel_hash)) {
break;
}
ran_at_least_once = true;
main_runner_->Run();
if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
break;
}
if (!ran_at_least_once) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
}
exit_code = 0;
} else {
exit_code = main_runner_->Run();
}
main_runner_->Shutdown();
return exit_code;
}
Commit Message: [content shell] reset the CWD after each layout test
BUG=111316
[email protected]
Review URL: https://codereview.chromium.org/11633017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173906 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 1
Example 2:
Code: void OmniboxViewWin::PlaceCaretAt(string16::size_type pos) {
SetSelection(static_cast<LONG>(pos), static_cast<LONG>(pos));
}
Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop.
BUG=109245
TEST=N/A
Review URL: http://codereview.chromium.org/9116016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
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: PlatformSensorProviderBase::MapSharedBufferForType(mojom::SensorType type) {
mojo::ScopedSharedBufferMapping mapping = shared_buffer_handle_->MapAtOffset(
kReadingBufferSize, SensorReadingSharedBuffer::GetOffset(type));
if (mapping)
memset(mapping.get(), 0, kReadingBufferSize);
return mapping;
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t SampleIterator::seekTo(uint32_t sampleIndex) {
ALOGV("seekTo(%d)", sampleIndex);
if (sampleIndex >= mTable->mNumSampleSizes) {
return ERROR_END_OF_STREAM;
}
if (mTable->mSampleToChunkOffset < 0
|| mTable->mChunkOffsetOffset < 0
|| mTable->mSampleSizeOffset < 0
|| mTable->mTimeToSampleCount == 0) {
return ERROR_MALFORMED;
}
if (mInitialized && mCurrentSampleIndex == sampleIndex) {
return OK;
}
if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) {
reset();
}
if (sampleIndex >= mStopChunkSampleIndex) {
status_t err;
if ((err = findChunkRange(sampleIndex)) != OK) {
ALOGE("findChunkRange failed");
return err;
}
}
CHECK(sampleIndex < mStopChunkSampleIndex);
if (mSamplesPerChunk == 0) {
ALOGE("b/22802344");
return ERROR_MALFORMED;
}
uint32_t chunk =
(sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk
+ mFirstChunk;
if (!mInitialized || chunk != mCurrentChunkIndex) {
mCurrentChunkIndex = chunk;
status_t err;
if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) {
ALOGE("getChunkOffset return error");
return err;
}
mCurrentChunkSampleSizes.clear();
uint32_t firstChunkSampleIndex =
mFirstChunkSampleIndex
+ mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk);
for (uint32_t i = 0; i < mSamplesPerChunk; ++i) {
size_t sampleSize;
if ((err = getSampleSizeDirect(
firstChunkSampleIndex + i, &sampleSize)) != OK) {
ALOGE("getSampleSizeDirect return error");
return err;
}
mCurrentChunkSampleSizes.push(sampleSize);
}
}
uint32_t chunkRelativeSampleIndex =
(sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk;
mCurrentSampleOffset = mCurrentChunkOffset;
for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) {
mCurrentSampleOffset += mCurrentChunkSampleSizes[i];
}
mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex];
if (sampleIndex < mTTSSampleIndex) {
mTimeToSampleIndex = 0;
mTTSSampleIndex = 0;
mTTSSampleTime = 0;
mTTSCount = 0;
mTTSDuration = 0;
}
status_t err;
if ((err = findSampleTimeAndDuration(
sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) {
ALOGE("findSampleTime return error");
return err;
}
mCurrentSampleIndex = sampleIndex;
mInitialized = true;
return OK;
}
Commit Message: SampleIterator: clear members on seekTo error
Bug: 31091777
Change-Id: Iddf99d0011961d0fd3d755e57db4365b6a6a1193
(cherry picked from commit 03237ce0f9584c98ccda76c2474a4ae84c763f5b)
CWE ID: CWE-200
Target: 1
Example 2:
Code: vmsWarningHandler(const char* module, const char* fmt, va_list ap)
{
if (module != NULL)
fprintf(stderr, "%s: ", module);
fprintf(stderr, "Warning, ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, ".\n");
}
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: 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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = (mWidth * mHeight * 3) / 2;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
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 tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
Commit Message:
CWE ID:
Target: 1
Example 2:
Code: static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
{
struct socket *sock = sk->sk_socket;
struct tipc_msg *msg = buf_msg(buf);
unsigned int limit = rcvbuf_limit(sk, buf);
u32 res = TIPC_OK;
/* Reject message if it is wrong sort of message for socket */
if (msg_type(msg) > TIPC_DIRECT_MSG)
return TIPC_ERR_NO_PORT;
if (sock->state == SS_READY) {
if (msg_connected(msg))
return TIPC_ERR_NO_PORT;
} else {
res = filter_connect(tipc_sk(sk), &buf);
if (res != TIPC_OK || buf == NULL)
return res;
}
/* Reject message if there isn't room to queue it */
if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
return TIPC_ERR_OVERLOAD;
/* Enqueue message */
TIPC_SKB_CB(buf)->handle = 0;
__skb_queue_tail(&sk->sk_receive_queue, buf);
skb_set_owner_r(buf, sk);
sk->sk_data_ready(sk, 0);
return TIPC_OK;
}
Commit Message: tipc: fix info leaks via msg_name in recv_msg/recv_stream
The code in set_orig_addr() does not initialize all of the members of
struct sockaddr_tipc when filling the sockaddr info -- namely the union
is only partly filled. This will make recv_msg() and recv_stream() --
the only users of this function -- leak kernel stack memory as the
msg_name member is a local variable in net/socket.c.
Additionally to that both recv_msg() and recv_stream() fail to update
the msg_namelen member to 0 while otherwise returning with 0, i.e.
"success". This is the case for, e.g., non-blocking sockets. This will
lead to a 128 byte kernel stack leak in net/socket.c.
Fix the first issue by initializing the memory of the union with
memset(0). Fix the second one by setting msg_namelen to 0 early as it
will be updated later if we're going to fill the msg_name member.
Cc: Jon Maloy <[email protected]>
Cc: Allan Stephens <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cifs_put_tcp_session(struct TCP_Server_Info *server)
{
struct task_struct *task;
write_lock(&cifs_tcp_ses_lock);
if (--server->srv_count > 0) {
write_unlock(&cifs_tcp_ses_lock);
return;
}
list_del_init(&server->tcp_ses_list);
write_unlock(&cifs_tcp_ses_lock);
spin_lock(&GlobalMid_Lock);
server->tcpStatus = CifsExiting;
spin_unlock(&GlobalMid_Lock);
cifs_fscache_release_client_cookie(server);
task = xchg(&server->tsk, NULL);
if (task)
force_sig(SIGKILL, task);
}
Commit Message: cifs: clean up cifs_find_smb_ses (try #2)
This patch replaces the earlier patch by the same name. The only
difference is that MAX_PASSWORD_SIZE has been increased to attempt to
match the limits that windows enforces.
Do a better job of matching sessions by authtype. Matching by username
for a Kerberos session is incorrect, and anonymous sessions need special
handling.
Also, in the case where we do match by username, we also need to match
by password. That ensures that someone else doesn't "borrow" an existing
session without needing to know the password.
Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE
to 512 to match the size that the userspace mount helper allows.
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[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: arp_print(netdissect_options *ndo,
const u_char *bp, u_int length, u_int caplen)
{
const struct arp_pkthdr *ap;
u_short pro, hrd, op, linkaddr;
ap = (const struct arp_pkthdr *)bp;
ND_TCHECK(*ap);
hrd = HRD(ap);
pro = PRO(ap);
op = OP(ap);
/* if its ATM then call the ATM ARP printer
for Frame-relay ARP most of the fields
are similar to Ethernet so overload the Ethernet Printer
and set the linkaddr type for linkaddr_string(ndo, ) accordingly */
switch(hrd) {
case ARPHRD_ATM2225:
atmarp_print(ndo, bp, length, caplen);
return;
case ARPHRD_FRELAY:
linkaddr = LINKADDR_FRELAY;
break;
default:
linkaddr = LINKADDR_ETHER;
break;
}
if (!ND_TTEST2(*ar_tpa(ap), PROTO_LEN(ap))) {
ND_PRINT((ndo, "%s", tstr));
ND_DEFAULTPRINT((const u_char *)ap, length);
return;
}
if (!ndo->ndo_eflag) {
ND_PRINT((ndo, "ARP, "));
}
/* print hardware type/len and proto type/len */
if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) ||
PROTO_LEN(ap) != 4 ||
HRD_LEN(ap) == 0 ||
ndo->ndo_vflag) {
ND_PRINT((ndo, "%s (len %u), %s (len %u)",
tok2str(arphrd_values, "Unknown Hardware (%u)", hrd),
HRD_LEN(ap),
tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro),
PROTO_LEN(ap)));
/* don't know know about the address formats */
if (!ndo->ndo_vflag) {
goto out;
}
}
/* print operation */
ND_PRINT((ndo, "%s%s ",
ndo->ndo_vflag ? ", " : "",
tok2str(arpop_values, "Unknown (%u)", op)));
switch (op) {
case ARPOP_REQUEST:
ND_PRINT((ndo, "who-has %s", ipaddr_string(ndo, TPA(ap))));
if (isnonzero((const u_char *)THA(ap), HRD_LEN(ap)))
ND_PRINT((ndo, " (%s)",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap))));
ND_PRINT((ndo, " tell %s", ipaddr_string(ndo, SPA(ap))));
break;
case ARPOP_REPLY:
ND_PRINT((ndo, "%s is-at %s",
ipaddr_string(ndo, SPA(ap)),
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_REVREQUEST:
ND_PRINT((ndo, "who-is %s tell %s",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)),
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_REVREPLY:
ND_PRINT((ndo, "%s at %s",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)),
ipaddr_string(ndo, TPA(ap))));
break;
case ARPOP_INVREQUEST:
ND_PRINT((ndo, "who-is %s tell %s",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)),
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_INVREPLY:
ND_PRINT((ndo,"%s at %s",
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)),
ipaddr_string(ndo, SPA(ap))));
break;
default:
ND_DEFAULTPRINT((const u_char *)ap, caplen);
return;
}
out:
ND_PRINT((ndo, ", length %u", length));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13013/ARP: Fix printing of ARP protocol addresses.
If the protocol type isn't ETHERTYPE_IP or ETHERTYPE_TRAIL, or if the
protocol address length isn't 4, don't print the address as an IPv4 address.
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), modified
so the capture file won't be rejected as an invalid capture.
Update another test file's tcpdump output to reflect this change.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int map_get_next_key(union bpf_attr *attr)
{
void __user *ukey = u64_to_ptr(attr->key);
void __user *unext_key = u64_to_ptr(attr->next_key);
int ufd = attr->map_fd;
struct bpf_map *map;
void *key, *next_key;
struct fd f;
int err;
if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
return -EINVAL;
f = fdget(ufd);
map = __bpf_map_get(f);
if (IS_ERR(map))
return PTR_ERR(map);
err = -ENOMEM;
key = kmalloc(map->key_size, GFP_USER);
if (!key)
goto err_put;
err = -EFAULT;
if (copy_from_user(key, ukey, map->key_size) != 0)
goto free_key;
err = -ENOMEM;
next_key = kmalloc(map->key_size, GFP_USER);
if (!next_key)
goto free_key;
rcu_read_lock();
err = map->ops->map_get_next_key(map, key, next_key);
rcu_read_unlock();
if (err)
goto free_next_key;
err = -EFAULT;
if (copy_to_user(unext_key, next_key, map->key_size) != 0)
goto free_next_key;
err = 0;
free_next_key:
kfree(next_key);
free_key:
kfree(key);
err_put:
fdput(f);
return err;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void qeth_close_dev(struct qeth_card *card)
{
QETH_CARD_TEXT(card, 2, "cldevsubm");
queue_work(qeth_wq, &card->close_dev_work);
}
Commit Message: qeth: avoid buffer overflow in snmp ioctl
Check user-defined length in snmp ioctl request and allow request
only if it fits into a qeth command buffer.
Signed-off-by: Ursula Braun <[email protected]>
Signed-off-by: Frank Blaschka <[email protected]>
Reviewed-by: Heiko Carstens <[email protected]>
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Cc: <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int hci_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
BT_DBG("sock %p, sk %p", sock, sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
if (sk->sk_state == BT_CLOSED)
return 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
return err;
msg->msg_namelen = 0;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
switch (hci_pi(sk)->channel) {
case HCI_CHANNEL_RAW:
hci_sock_cmsg(sk, msg, skb);
break;
case HCI_CHANNEL_USER:
case HCI_CHANNEL_CONTROL:
case HCI_CHANNEL_MONITOR:
sock_recv_timestamp(msg, sk, skb);
break;
}
skb_free_datagram(sk, skb);
return err ? : copied;
}
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: 1
Example 2:
Code: int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
{
SSL3_RECORD *rec;
EVP_CIPHER_CTX *ds;
unsigned long l;
int bs, i, mac_size = 0;
const EVP_CIPHER *enc;
rec = inrecs;
/*
* We shouldn't ever be called with more than one record in the SSLv3 case
*/
if (n_recs != 1)
return 0;
if (send) {
ds = s->enc_write_ctx;
if (s->enc_write_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
} else {
ds = s->enc_read_ctx;
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
memmove(rec->data, rec->input, rec->length);
rec->input = rec->data;
} else {
l = rec->length;
bs = EVP_CIPHER_CTX_block_size(ds);
/* COMPRESS */
if ((bs != 1) && send) {
i = bs - ((int)l % bs);
/* we need to add 'i-1' padding bytes */
l += i;
/*
* the last of these zero bytes will be overwritten with the
* padding length.
*/
memset(&rec->input[rec->length], 0, i);
rec->length += i;
rec->input[l - 1] = (i - 1);
}
if (!send) {
if (l == 0 || l % bs != 0)
return 0;
/* otherwise, rec->length >= bs */
}
if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
return -1;
if (EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send)
return ssl3_cbc_remove_padding(rec, bs, mac_size);
}
return (1);
}
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: wv_csp10_opaque_binary_tag(tvbuff_t *tvb, guint32 offset,
guint8 token, guint8 codepage, guint32 *length)
{
guint32 data_len = tvb_get_guintvar(tvb, offset, length);
char *str = NULL;
switch (codepage) {
case 0: /* Common code page */
switch (token) {
case 0x0B: /* <Code> */
case 0x0F: /* <ContentSize> */
case 0x1A: /* <MessageCount> */
case 0x3C: /* <Validity> */
str = wv_integer_from_opaque(tvb,
offset + *length, data_len);
break;
case 0x11: /* <DateTime> */
str = wv_datetime_from_opaque(tvb,
offset + *length, data_len);
break;
default:
break;
}
break;
case 1: /* Access code page */
switch (token) {
case 0x1C: /* <KeepAliveTime> */
case 0x32: /* <TimeToLive> */
str = wv_integer_from_opaque(tvb,
offset + *length, data_len);
break;
default:
break;
}
break;
case 3: /* Client capability code page */
switch (token) {
case 0x06: /* <AcceptedContentLength> */
case 0x0C: /* <MultiTrans> */
case 0x0D: /* <ParserSize> */
case 0x0E: /* <ServerPollMin> */
case 0x11: /* <TCPAddress> */
case 0x12: /* <TCPPort> */
case 0x13: /* <UDPPort> */
str = wv_integer_from_opaque(tvb,
offset + *length, data_len);
break;
default:
break;
}
break;
default:
break;
}
if (str == NULL) { /* Error, or not parsed */
str = wmem_strdup_printf(wmem_packet_scope(), "(%d bytes of unparsed opaque data)", data_len);
}
*length += data_len;
return str;
}
Commit Message: WBXML: add a basic sanity check for offset overflow
This is a naive approach allowing to detact that something went wrong,
without the need to replace all proto_tree_add_text() calls as what was
done in master-2.0 branch.
Bug: 12408
Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108
Reviewed-on: https://code.wireshark.org/review/15310
Reviewed-by: Michael Mann <[email protected]>
Reviewed-by: Pascal Quantin <[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: InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
return input_method_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: void Update(BytesConsumer* consumer) {
DCHECK(!underlying_);
if (is_cancelled_) {
return;
}
underlying_ = consumer;
if (client_) {
Client* client = client_;
client_ = nullptr;
underlying_->SetClient(client);
if (GetPublicState() != PublicState::kReadableOrWaiting)
client->OnStateChange();
}
}
Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests
The spec issue is now fixed, and this CL follows the spec change[1].
1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d
Bug: 791324
Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb
Reviewed-on: https://chromium-review.googlesource.com/1023613
Reviewed-by: Tsuyoshi Horo <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552964}
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: WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand,
const char *option,const char *arg1n,const char *arg2n)
{
const char /* percent escaped versions of the args */
*arg1,
*arg2;
Image
*new_images;
MagickStatusType
status;
ssize_t
parse;
#define _image_info (cli_wand->wand.image_info)
#define _images (cli_wand->wand.images)
#define _exception (cli_wand->wand.exception)
#define _draw_info (cli_wand->draw_info)
#define _quantize_info (cli_wand->quantize_info)
#define _process_flags (cli_wand->process_flags)
#define _option_type ((CommandOptionFlags) cli_wand->command->flags)
#define IfNormalOp (*option=='-')
#define IfPlusOp (*option!='-')
#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
assert(cli_wand->wand.signature == MagickWandSignature);
assert(_images != (Image *) NULL); /* _images must be present */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- List Operator: %s \"%s\" \"%s\"", option,
arg1n == (const char *) NULL ? "null" : arg1n,
arg2n == (const char *) NULL ? "null" : arg2n);
arg1 = arg1n;
arg2 = arg2n;
/* Interpret Percent Escapes in Arguments - using first image */
if ( (((_process_flags & ProcessInterpretProperities) != 0 )
|| ((_option_type & AlwaysInterpretArgsFlag) != 0)
) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {
/* Interpret Percent escapes in argument 1 */
if (arg1n != (char *) NULL) {
arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);
if (arg1 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg1=arg1n; /* use the given argument as is */
}
}
if (arg2n != (char *) NULL) {
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg2=arg2n; /* use the given argument as is */
}
}
}
#undef _process_flags
#undef _option_type
status=MagickTrue;
new_images=NewImageList();
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("append",option+1) == 0)
{
new_images=AppendImages(_images,IsNormalOp,_exception);
break;
}
if (LocaleCompare("average",option+1) == 0)
{
CLIWandWarnReplaced("-evaluate-sequence Mean");
(void) CLIListOperatorImages(cli_wand,"-evaluate-sequence","Mean",
NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
new_images=ChannelFxImage(_images,arg1,_exception);
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image;
/* FUTURE - make this a compose option, and thus can be used
with layers compose or even compose last image over all other
_images.
*/
new_images=RemoveFirstImageFromList(&_images);
clut_image=RemoveLastImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (clut_image == (Image *) NULL)
break;
(void) ClutImage(new_images,clut_image,new_images->interpolate,
_exception);
clut_image=DestroyImage(clut_image);
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
new_images=CoalesceImages(_images,_exception);
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
parse=(ssize_t) _images->colorspace;
if (_images->number_channels < GetImageListLength(_images))
parse=sRGBColorspace;
if ( IfPlusOp )
parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedColorspace",option,
arg1);
new_images=CombineImages(_images,(ColorspaceType) parse,_exception);
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
image=RemoveFirstImageFromList(&_images);
reconstruct_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (reconstruct_image == (Image *) NULL)
{
image=DestroyImage(image);
break;
}
metric=UndefinedErrorMetric;
option=GetImageOption(_image_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
new_images=CompareImages(image,reconstruct_image,metric,&distortion,
_exception);
(void) distortion;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=ComplexImages(_images,(ComplexOperator) parse,_exception);
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
value=GetImageOption(_image_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
clip_to_self=GetCompositeClipToSelf(compose);
value=GetImageOption(_image_info,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsStringTrue(value);
value=GetImageOption(_image_info,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsStringFalse(value); /* deprecated */
new_images=RemoveFirstImageFromList(&_images);
source_image=RemoveFirstImageFromList(&_images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE - this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,_exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,_exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity, &geometry);
mask_image=RemoveFirstImageFromList(&_images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,clip_to_self,
geometry.x,geometry.y,_exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,_exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(clone_image,new_images,OverCompositeOp,
clip_to_self,0,0,_exception);
new_images=DestroyImageList(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
if (IsGeometry(arg2) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
(void) ParsePageGeometry(_images,arg2,&geometry,_exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=_images;
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,arg1,&geometry,_exception);
(void) CopyImagePixels(_images,source_image,&geometry,&offset,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
CLIWandWarnReplaced("-layer CompareAny");
(void) CLIListOperatorImages(cli_wand,"-layer","CompareAny",NULL);
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (IfNormalOp)
DeleteImages(&_images,arg1,_exception);
else
DeleteImages(&_images,"-1",_exception);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
if (IfNormalOp)
{
const char
*p;
size_t
number_duplicates;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,
arg1);
number_duplicates=(size_t) StringToLong(arg1);
p=strchr(arg1,',');
if (p == (const char *) NULL)
new_images=DuplicateImages(_images,number_duplicates,"-1",
_exception);
else
new_images=DuplicateImages(_images,number_duplicates,p,
_exception);
}
else
new_images=DuplicateImages(_images,1,"-1",_exception);
AppendImageToList(&_images, new_images);
new_images=(Image *) NULL;
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
new_images=ForwardFourierTransformImage(_images,IsNormalOp,
_exception);
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
/* REDIRECTED to use -layers flatten instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
new_images=FxImage(_images,arg1,_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
/* FUTURE - make this a compose option (and thus layers compose )
or perhaps compose last image over all other _images.
*/
Image
*hald_image;
new_images=RemoveFirstImageFromList(&_images);
hald_image=RemoveLastImageFromList(&_images);
if (hald_image == (Image *) NULL)
break;
(void) HaldClutImage(new_images,hald_image,_exception);
hald_image=DestroyImage(hald_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*magnitude_image,
*phase_image;
magnitude_image=RemoveFirstImageFromList(&_images);
phase_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (phase_image == (Image *) NULL)
break;
new_images=InverseFourierTransformImage(magnitude_image,phase_image,
IsNormalOp,_exception);
magnitude_image=DestroyImage(magnitude_image);
phase_image=DestroyImage(phase_image);
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*insert_image,
*index_image;
ssize_t
index;
if (IfNormalOp && (IsGeometry(arg1) == MagickFalse))
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=0;
insert_image=RemoveLastImageFromList(&_images);
if (IfNormalOp)
index=(ssize_t) StringToLong(arg1);
index_image=insert_image;
if (index == 0)
PrependImageToList(&_images,insert_image);
else if (index == (ssize_t) GetImageListLength(_images))
AppendImageToList(&_images,insert_image);
else
{
index_image=GetImageFromList(_images,index-1);
if (index_image == (Image *) NULL)
CLIWandExceptArgBreak(OptionError,"NoSuchImage",option,arg1);
InsertImageInList(&index_image,insert_image);
}
_images=GetFirstImageInList(index_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1);
if ( parse < 0 )
CLIWandExceptArgBreak(OptionError,"UnrecognizedLayerMethod",
option,arg1);
switch ((LayerMethod) parse)
{
case CoalesceLayer:
{
new_images=CoalesceImages(_images,_exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
new_images=CompareImagesLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
new_images=MergeImageLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case DisposeLayer:
{
new_images=DisposeImages(_images,_exception);
break;
}
case OptimizeImageLayer:
{
new_images=OptimizeImageLayers(_images,_exception);
break;
}
case OptimizePlusLayer:
{
new_images=OptimizePlusImageLayers(_images,_exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(_images,_exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(&_images,_exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(&_images,_exception);
break;
}
case OptimizeLayer:
{ /* General Purpose, GIF Animation Optimizer. */
new_images=CoalesceImages(_images,_exception);
if (new_images == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=OptimizeImageLayers(new_images,_exception);
if (_images == (Image *) NULL)
break;
new_images=DestroyImageList(new_images);
OptimizeImageTransparency(_images,_exception);
(void) RemapImages(_quantize_info,_images,(Image *) NULL,
_exception);
break;
}
case CompositeLayer:
{
Image
*source;
RectangleInfo
geometry;
CompositeOperator
compose;
const char*
value;
value=GetImageOption(_image_info,"compose");
compose=OverCompositeOp; /* Default to Over */
if (value != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Split image sequence at the first 'NULL:' image. */
source=_images;
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{ /* Separate the two lists, junk the null: image. */
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(_exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
break;
}
/* Adjust offset with gravity and virtual canvas. */
SetGeometry(_images,&geometry);
(void) ParseAbsoluteGeometry(_images->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry(_images->page.width != 0 ?
_images->page.width : _images->columns,
_images->page.height != 0 ? _images->page.height :
_images->rows,_images->gravity,&geometry);
/* Compose the two image sequences together */
CompositeLayers(_images,compose,source,geometry.x,geometry.y,
_exception);
source=DestroyImageList(source);
break;
}
}
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
CLIWandWarnReplaced("+remap");
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("metric",option+1) == 0)
{
(void) SetImageOption(_image_info,option+1,arg1);
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
morph_image=MorphImages(_images,StringToUnsignedLong(arg1),
_exception);
if (morph_image == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
/* REDIRECTED to use -layers mosaic instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
double
*args;
ssize_t
count;
/* convert argument string into an array of doubles */
args = StringToArrayOfDoubles(arg1,&count,_exception);
if (args == (double *) NULL )
CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg1);
new_images=PolynomialImage(_images,(size_t) (count >> 1),args,
_exception);
args=(double *) RelinquishMagickMemory(args);
break;
}
if (LocaleCompare("process",option+1) == 0)
{
/* FUTURE: better parsing using ScriptToken() from string ??? */
char
**arguments;
int
j,
number_arguments;
arguments=StringToArgv(arg1,&number_arguments);
if (arguments == (char **) NULL)
break;
if (strchr(arguments[1],'=') != (char *) NULL)
{
char
breaker,
quote,
*token;
const char
*arguments;
int
next,
status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg1".
*/
assert(arg1 != (const char *) NULL);
length=strlen(arg1);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
arguments=arg1;
token_info=AcquireTokenInfo();
status=Tokenizer(token_info,0,token,length,arguments,"","=",
"\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (status == 0)
{
const char
*argv;
argv=(&(arguments[next]));
(void) InvokeDynamicImageFilter(token,&_images,1,&argv,
_exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&_images,
number_arguments-2,(const char **) arguments+2,_exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'r':
{
if (LocaleCompare("remap",option+1) == 0)
{
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(&_images);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
/* FUTURE: this option needs more work to make better */
ssize_t
offset;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
offset=(ssize_t) StringToLong(arg1);
new_images=SmushImages(_images,IsNormalOp,offset,_exception);
break;
}
if (LocaleCompare("subimage",option+1) == 0)
{
Image
*base_image,
*compare_image;
const char
*value;
MetricType
metric;
double
similarity;
RectangleInfo
offset;
base_image=GetImageFromList(_images,0);
compare_image=GetImageFromList(_images,1);
/* Comparision Metric */
metric=UndefinedErrorMetric;
value=GetImageOption(_image_info,"metric");
if (value != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,value);
new_images=SimilarityImage(base_image,compare_image,metric,0.0,
&offset,&similarity,_exception);
if (new_images != (Image *) NULL)
{
char
result[MagickPathExtent];
(void) FormatLocaleString(result,MagickPathExtent,"%lf",
similarity);
(void) SetImageProperty(new_images,"subimage:similarity",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.x);
(void) SetImageProperty(new_images,"subimage:x",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.y);
(void) SetImageProperty(new_images,"subimage:y",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,
"%lux%lu%+ld%+ld",(unsigned long) offset.width,(unsigned long)
offset.height,(long) offset.x,(long) offset.y);
(void) SetImageProperty(new_images,"subimage:offset",result,
_exception);
}
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
index=(-1);
swap_index=(-2);
if (IfNormalOp) {
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(arg1,&geometry_info);
if ((flags & RhoValue) == 0)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(_images,index);
q=GetImageFromList(_images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL)) {
if (IfNormalOp)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1)
else
CLIWandExceptionBreak(OptionError,"TwoOrMoreImagesRequired",option);
}
if (p == q)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1);
swap=CloneImage(p,0,0,MagickTrue,_exception);
if (swap == (Image *) NULL)
CLIWandExceptArgBreak(ResourceLimitError,"MemoryAllocationFailed",
option,GetExceptionMessage(errno));
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception));
ReplaceImageInList(&q,swap);
_images=GetFirstImageInList(q);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
default:
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
/* clean up percent escape interpreted strings */
if (arg1 != arg1n )
arg1=DestroyString((char *)arg1);
if (arg2 != arg2n )
arg2=DestroyString((char *)arg2);
/* if new image list generated, replace existing image list */
if (new_images == (Image *) NULL)
return(status == 0 ? MagickFalse : MagickTrue);
_images=DestroyImageList(_images);
_images=GetFirstImageInList(new_images);
return(status == 0 ? MagickFalse : MagickTrue);
#undef _image_info
#undef _images
#undef _exception
#undef _draw_info
#undef _quantize_info
#undef IfNormalOp
#undef IfPlusOp
#undef IsNormalOp
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1616
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 AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match,
WindowOpenDisposition disposition,
const GURL& alternate_nav_url,
size_t index) {
if (popup_->IsOpen()) {
AutocompleteLog log(
autocomplete_controller_->input().text(),
just_deleted_text_,
autocomplete_controller_->input().type(),
popup_->selected_line(),
-1, // don't yet know tab ID; set later if appropriate
ClassifyPage(controller_->GetTabContentsWrapper()->
web_contents()->GetURL()),
base::TimeTicks::Now() - time_user_first_modified_omnibox_,
0, // inline autocomplete length; possibly set later
result());
DCHECK(user_input_in_progress_) << "We didn't get here through the "
"expected series of calls. time_user_first_modified_omnibox_ is "
"not set correctly and other things may be wrong.";
if (index != AutocompletePopupModel::kNoMatch)
log.selected_index = index;
else if (!has_temporary_text_)
log.inline_autocompleted_length = inline_autocomplete_text_.length();
if (disposition == CURRENT_TAB) {
log.tab_id = controller_->GetTabContentsWrapper()->
restore_tab_helper()->session_id().id();
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::Source<Profile>(profile_),
content::Details<AutocompleteLog>(&log));
}
TemplateURL* template_url = match.GetTemplateURL(profile_);
if (template_url) {
if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
if (template_url->IsExtensionKeyword()) {
AutocompleteMatch current_match;
GetInfoForCurrentText(¤t_match, NULL);
const AutocompleteMatch& match =
(index == AutocompletePopupModel::kNoMatch) ?
current_match : result().match_at(index);
size_t prefix_length = match.keyword.length() + 1;
extensions::ExtensionOmniboxEventRouter::OnInputEntered(profile_,
template_url->GetExtensionId(),
UTF16ToUTF8(match.fill_into_edit.substr(prefix_length)));
view_->RevertAll();
return;
}
content::RecordAction(UserMetricsAction("AcceptedKeyword"));
TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
template_url);
} else {
DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
}
UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
template_url->prepopulate_id(),
TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
}
if (disposition != NEW_BACKGROUND_TAB) {
in_revert_ = true;
view_->RevertAll(); // Revert the box to its unedited state
}
if (match.type == AutocompleteMatch::EXTENSION_APP) {
extensions::LaunchAppFromOmnibox(match, profile_, disposition);
} else {
controller_->OnAutocompleteAccept(match.destination_url, disposition,
match.transition, alternate_nav_url);
}
if (match.starred)
bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);
InstantController* instant = controller_->GetInstant();
if (instant && !popup_->IsOpen())
instant->DestroyPreviewContents();
in_revert_ = false;
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: void WebGLRenderingContextBase::uniformMatrix3fv(
const WebGLUniformLocation* location,
GLboolean transpose,
Vector<GLfloat>& v) {
if (isContextLost() ||
!ValidateUniformMatrixParameters("uniformMatrix3fv", location, transpose,
v.data(), v.size(), 9, 0, v.size()))
return;
ContextGL()->UniformMatrix3fv(location->Location(), v.size() / 9, transpose,
v.data());
}
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
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodReturningSequence(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"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = jsArray(exec, castedThis->globalObject(), impl->methodReturningSequence(intArg));
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
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: SPL_METHOD(SplFileInfo, getPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *path;
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
RETURN_STRINGL(path, path_len, 1);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: lseg_dt(LSEG *l1, LSEG *l2)
{
double result,
d;
if (lseg_intersect_internal(l1, l2))
return 0.0;
d = dist_ps_internal(&l1->p[0], l2);
result = d;
d = dist_ps_internal(&l1->p[1], l2);
result = Min(result, d);
d = dist_ps_internal(&l2->p[0], l1);
result = Min(result, d);
d = dist_ps_internal(&l2->p[1], l1);
result = Min(result, d);
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: int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
{
struct ip_tunnel_info *info;
if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
return -EINVAL;
info = skb_tunnel_info_unclone(skb);
if (!info)
return -ENOMEM;
if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
return -EINVAL;
return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400
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 *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*tiff_pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point");
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black");
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white");
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette");
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB");
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB");
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV");
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK");
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated");
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR");
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown");
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric"));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb");
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb");
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace);
TIFFGetProfiles(tiff,image,image_info->ping);
TIFFGetProperties(tiff,image);
option=GetImageOption(image_info,"tiff:exif-properties");
if ((option == (const char *) NULL) ||
(IsMagickTrue(option) != MagickFalse))
TIFFGetEXIFProperties(tiff,image);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->x_resolution=x_resolution;
image->y_resolution=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5);
image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MaxTextExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
quantum_info=(QuantumInfo *) NULL;
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
goto next_tiff_frame;
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified");
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->matte=MagickTrue;
}
else
for (i=0; i < extra_samples; i++)
{
image->matte=MagickTrue;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated");
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated");
}
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MaxTextExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int)
rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value);
}
if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
tiff_pixels=(unsigned char *) AcquireMagickMemory(TIFFScanlineSize(tiff)+
sizeof(uint32));
if (tiff_pixels == (unsigned char *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->matte != MagickFalse)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
bits_per_sample)/log(2))));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
tiff_pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register IndexPacket
*indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=tiff_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)));
SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)));
SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)));
SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));
q++;
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) tiff_pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass);
number_pixels=(MagickSizeType) columns*rows;
if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
PixelPacket
*tile;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+(image->columns*(rows_remaining-1)+x);
for (row=rows_remaining; row > 0; row--)
{
if (image->matte != MagickFalse)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)));
q++;
p++;
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
q++;
p++;
}
p+=columns-columns_remaining;
q-=(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=image->columns-1;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
p--;
q--;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels);
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image = DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
Commit Message: https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31161
CWE ID: CWE-119
Target: 1
Example 2:
Code: LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
{
LayoutUnit logicalTop = lastLogicalTop;
LayoutUnit logicalHeight = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalBottom - logicalTop;
if (logicalHeight <= 0)
return LayoutRect();
LayoutUnit logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
LayoutUnit logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
LayoutUnit logicalWidth = logicalRight - logicalLeft;
if (logicalWidth <= 0)
return LayoutRect();
LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selectionBackgroundColor());
return gapRect;
}
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: int vnc_display_password(DisplayState *ds, const char *password)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -EINVAL;
}
if (vs->auth == VNC_AUTH_NONE) {
error_printf_unless_qmp("If you want use passwords please enable "
"password auth using '-vnc ${dpy},password'.");
return -EINVAL;
}
g_free(vs->password);
vs->password = g_strdup(password);
return 0;
}
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: SSLErrorInfo SSLErrorInfo::CreateError(ErrorType error_type,
net::X509Certificate* cert,
const GURL& request_url) {
string16 title, details, short_description;
std::vector<string16> extra_info;
switch (error_type) {
case CERT_COMMON_NAME_INVALID: {
title =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_TITLE);
std::vector<std::string> dns_names;
cert->GetDNSNames(&dns_names);
DCHECK(!dns_names.empty());
size_t i = 0;
for (; i < dns_names.size(); ++i) {
if (dns_names[i] == cert->subject().common_name)
break;
}
if (i == dns_names.size())
i = 0;
details =
l10n_util::GetStringFUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_DETAILS,
UTF8ToUTF16(request_url.host()),
UTF8ToUTF16(dns_names[i]),
UTF8ToUTF16(request_url.host()));
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_COMMON_NAME_INVALID_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(
l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_COMMON_NAME_INVALID_EXTRA_INFO_2,
UTF8ToUTF16(cert->subject().common_name),
UTF8ToUTF16(request_url.host())));
break;
}
case CERT_DATE_INVALID:
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
if (cert->HasExpired()) {
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_EXPIRED_DETAILS,
UTF8ToUTF16(request_url.host()),
UTF8ToUTF16(request_url.host()),
base::TimeFormatFriendlyDateAndTime(base::Time::Now()));
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_DESCRIPTION);
extra_info.push_back(l10n_util::GetStringUTF16(
IDS_CERT_ERROR_EXPIRED_DETAILS_EXTRA_INFO_2));
} else {
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_NOT_YET_VALID_DETAILS,
UTF8ToUTF16(request_url.host()),
UTF8ToUTF16(request_url.host()),
base::TimeFormatFriendlyDateAndTime(base::Time::Now()));
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(
IDS_CERT_ERROR_NOT_YET_VALID_DETAILS_EXTRA_INFO_2));
}
break;
case CERT_AUTHORITY_INVALID:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_AUTHORITY_INVALID_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_AUTHORITY_INVALID_DETAILS,
UTF8ToUTF16(request_url.host()));
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_AUTHORITY_INVALID_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_2,
UTF8ToUTF16(request_url.host()),
UTF8ToUTF16(request_url.host())));
extra_info.push_back(l10n_util::GetStringUTF16(
IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_3));
break;
case CERT_CONTAINS_ERRORS:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_CONTAINS_ERRORS_DETAILS,
UTF8ToUTF16(request_url.host()));
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringFUTF16(IDS_CERT_ERROR_EXTRA_INFO_1,
UTF8ToUTF16(request_url.host())));
extra_info.push_back(l10n_util::GetStringUTF16(
IDS_CERT_ERROR_CONTAINS_ERRORS_EXTRA_INFO_2));
break;
case CERT_NO_REVOCATION_MECHANISM:
title = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_TITLE);
details = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DETAILS);
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DESCRIPTION);
break;
case CERT_UNABLE_TO_CHECK_REVOCATION:
title = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_TITLE);
details = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DETAILS);
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DESCRIPTION);
break;
case CERT_REVOKED:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_TITLE);
details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_REVOKED_CERT_DETAILS,
UTF8ToUTF16(request_url.host()));
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_EXTRA_INFO_2));
break;
case CERT_INVALID:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_INVALID_CERT_DETAILS,
UTF8ToUTF16(request_url.host()));
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(l10n_util::GetStringUTF16(
IDS_CERT_ERROR_INVALID_CERT_EXTRA_INFO_2));
break;
case CERT_WEAK_SIGNATURE_ALGORITHM:
title = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DETAILS,
UTF8ToUTF16(request_url.host()));
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(
l10n_util::GetStringUTF16(
IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_EXTRA_INFO_2));
break;
case CERT_WEAK_KEY:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_WEAK_KEY_TITLE);
details = l10n_util::GetStringFUTF16(
IDS_CERT_ERROR_WEAK_KEY_DETAILS, UTF8ToUTF16(request_url.host()));
short_description = l10n_util::GetStringUTF16(
IDS_CERT_ERROR_WEAK_KEY_DESCRIPTION);
extra_info.push_back(
l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1));
extra_info.push_back(
l10n_util::GetStringUTF16(
IDS_CERT_ERROR_WEAK_KEY_EXTRA_INFO_2));
break;
case UNKNOWN:
title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_TITLE);
details = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DETAILS);
short_description =
l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DESCRIPTION);
break;
default:
NOTREACHED();
}
return SSLErrorInfo(title, details, short_description, extra_info);
}
Commit Message: Properly EscapeForHTML potentially malicious input from X.509 certificates.
BUG=142956
TEST=Create an X.509 certificate with a CN field that contains JavaScript.
When you get the SSL error screen, check that the HTML + JavaScript is
escape instead of being treated as HTML and/or script.
Review URL: https://chromiumcodereview.appspot.com/10827364
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152210 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
Target: 1
Example 2:
Code: string_has_highlight (const char *string, const char *highlight_words)
{
char *msg, *highlight, *match, *match_pre, *match_post, *msg_pos;
char *pos, *pos_end, *ptr_str, *ptr_string_ref;
int end, length, startswith, endswith, wildcard_start, wildcard_end, flags;
if (!string || !string[0] || !highlight_words || !highlight_words[0])
return 0;
msg = strdup (string);
if (!msg)
return 0;
string_tolower (msg);
highlight = strdup (highlight_words);
if (!highlight)
{
free (msg);
return 0;
}
string_tolower (highlight);
pos = highlight;
end = 0;
while (!end)
{
ptr_string_ref = (char *)string;
flags = 0;
pos = (char *)string_regex_flags (pos, REG_ICASE, &flags);
pos_end = strchr (pos, ',');
if (!pos_end)
{
pos_end = strchr (pos, '\0');
end = 1;
}
/* error parsing string! */
if (!pos_end)
{
free (msg);
free (highlight);
return 0;
}
if (flags & REG_ICASE)
{
for (ptr_str = pos; ptr_str < pos_end; ptr_str++)
{
if ((ptr_str[0] >= 'A') && (ptr_str[0] <= 'Z'))
ptr_str[0] += ('a' - 'A');
}
ptr_string_ref = msg;
}
length = pos_end - pos;
pos_end[0] = '\0';
if (length > 0)
{
if ((wildcard_start = (pos[0] == '*')))
{
pos++;
length--;
}
if ((wildcard_end = (*(pos_end - 1) == '*')))
{
*(pos_end - 1) = '\0';
length--;
}
}
if (length > 0)
{
msg_pos = ptr_string_ref;
/* highlight found! */
while ((match = strstr (msg_pos, pos)) != NULL)
{
match_pre = utf8_prev_char (ptr_string_ref, match);
if (!match_pre)
match_pre = match - 1;
match_post = match + length;
startswith = ((match == ptr_string_ref) || (!string_is_word_char (match_pre)));
endswith = ((!match_post[0]) || (!string_is_word_char (match_post)));
if ((wildcard_start && wildcard_end) ||
(!wildcard_start && !wildcard_end &&
startswith && endswith) ||
(wildcard_start && endswith) ||
(wildcard_end && startswith))
{
free (msg);
free (highlight);
return 1;
}
msg_pos = match_post;
}
}
if (!end)
pos = pos_end + 1;
}
free (msg);
free (highlight);
/* no highlight found */
return 0;
}
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 FrameView::setCursor(const Cursor& cursor)
{
Page* page = frame().page();
if (!page || !page->settings().deviceSupportsMouse())
return;
page->chrome().setCursor(cursor);
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
[email protected]
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
uint32_t plane_checksum[4] = {0}, checksum = 0;
int i, plane, vsub = desc->log2_chroma_h;
for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane);
uint8_t *data = frame->data[plane];
int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
if (linesize < 0)
return linesize;
for (i = 0; i < h; i++) {
plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
checksum = av_adler32_update(checksum, data, linesize);
data += frame->linesize[plane];
}
}
av_log(ctx, AV_LOG_INFO,
"n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
"fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
"checksum:%08X plane_checksum:[%08X",
inlink->frame_count,
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame),
desc->name,
frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den,
frame->width, frame->height,
!frame->interlaced_frame ? 'P' : /* Progressive */
frame->top_field_first ? 'T' : 'B', /* Top / Bottom */
frame->key_frame,
av_get_picture_type_char(frame->pict_type),
checksum, plane_checksum[0]);
for (plane = 1; plane < 4 && frame->data[plane]; plane++)
av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
av_log(ctx, AV_LOG_INFO, "]\n");
return ff_filter_frame(inlink->dst->outputs[0], frame);
}
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: static int nntp_attempt_features(struct NntpServer *nserv)
{
struct Connection *conn = nserv->conn;
char buf[LONG_STRING];
/* no CAPABILITIES, trying DATE, LISTGROUP, LIST NEWSGROUPS */
if (!nserv->hasCAPABILITIES)
{
if (mutt_socket_send(conn, "DATE\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("500", buf, 3) != 0)
nserv->hasDATE = true;
if (mutt_socket_send(conn, "LISTGROUP\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("500", buf, 3) != 0)
nserv->hasLISTGROUP = true;
if (mutt_socket_send(conn, "LIST NEWSGROUPS +\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("500", buf, 3) != 0)
nserv->hasLIST_NEWSGROUPS = true;
if (mutt_str_strncmp("215", buf, 3) == 0)
{
do
{
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(nserv);
} while (mutt_str_strcmp(".", buf) != 0);
}
}
/* no LIST NEWSGROUPS, trying XGTITLE */
if (!nserv->hasLIST_NEWSGROUPS)
{
if (mutt_socket_send(conn, "XGTITLE\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("500", buf, 3) != 0)
nserv->hasXGTITLE = true;
}
/* no OVER, trying XOVER */
if (!nserv->hasOVER)
{
if (mutt_socket_send(conn, "XOVER\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("500", buf, 3) != 0)
nserv->hasXOVER = true;
}
/* trying LIST OVERVIEW.FMT */
if (nserv->hasOVER || nserv->hasXOVER)
{
if (mutt_socket_send(conn, "LIST OVERVIEW.FMT\r\n") < 0 ||
mutt_socket_readln(buf, sizeof(buf), conn) < 0)
{
return nntp_connect_error(nserv);
}
if (mutt_str_strncmp("215", buf, 3) != 0)
nserv->overview_fmt = OverviewFmt;
else
{
int cont = 0;
size_t buflen = 2 * LONG_STRING, off = 0, b = 0;
if (nserv->overview_fmt)
FREE(&nserv->overview_fmt);
nserv->overview_fmt = mutt_mem_malloc(buflen);
while (true)
{
if (buflen - off < LONG_STRING)
{
buflen *= 2;
mutt_mem_realloc(&nserv->overview_fmt, buflen);
}
const int chunk =
mutt_socket_readln(nserv->overview_fmt + off, buflen - off, conn);
if (chunk < 0)
{
FREE(&nserv->overview_fmt);
return nntp_connect_error(nserv);
}
if (!cont && (mutt_str_strcmp(".", nserv->overview_fmt + off) == 0))
break;
cont = chunk >= buflen - off ? 1 : 0;
off += strlen(nserv->overview_fmt + off);
if (!cont)
{
char *colon = NULL;
if (nserv->overview_fmt[b] == ':')
{
memmove(nserv->overview_fmt + b, nserv->overview_fmt + b + 1, off - b - 1);
nserv->overview_fmt[off - 1] = ':';
}
colon = strchr(nserv->overview_fmt + b, ':');
if (!colon)
nserv->overview_fmt[off++] = ':';
else if (strcmp(colon + 1, "full") != 0)
off = colon + 1 - nserv->overview_fmt;
if (strcasecmp(nserv->overview_fmt + b, "Bytes:") == 0)
{
size_t len = strlen(nserv->overview_fmt + b);
mutt_str_strfcpy(nserv->overview_fmt + b, "Content-Length:", len + 1);
off = b + len;
}
nserv->overview_fmt[off++] = '\0';
b = off;
}
}
nserv->overview_fmt[off++] = '\0';
mutt_mem_realloc(&nserv->overview_fmt, off);
}
}
return 0;
}
Commit Message: Add alloc fail check in nntp_fetch_headers
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: capture_ppi(const guchar *pd, int len, packet_counts *ld)
{
guint32 dlt;
guint ppi_len;
ppi_len = pletoh16(pd+2);
if(ppi_len < PPI_V0_HEADER_LEN || !BYTES_ARE_IN_FRAME(0, len, ppi_len)) {
ld->other++;
return;
}
dlt = pletoh32(pd+4);
/* XXX - We should probably combine this with capture_info.c:capture_info_packet() */
switch(dlt) {
case 1: /* DLT_EN10MB */
capture_eth(pd, ppi_len, len, ld);
return;
case 105: /* DLT_DLT_IEEE802_11 */
capture_ieee80211(pd, ppi_len, len, ld);
return;
default:
break;
}
ld->other++;
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <[email protected]>
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: MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_width=1.0;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_rule=EvenOddRule;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(Quantum) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
draw_info->stroke_antialias=clone_info->antialias;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (clone_info->pointsize != 0.0)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
Commit Message: Prevent buffer overflow in magick/draw.c
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool HTMLInputElement::IsKeyboardFocusable() const {
return input_type_->IsKeyboardFocusable();
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationReplaceable());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
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: | 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_MINIT_FUNCTION(xml)
{
le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number);
REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT);
/* this object should not be pre-initialised at compile time,
as the order of members may vary */
php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper;
php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper;
php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper;
#ifdef LIBXML_EXPAT_COMPAT
REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT);
#else
REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT);
#endif
return SUCCESS;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AppLayerProtoDetectRegisterProtocol(AppProto alproto, const char *alproto_name)
{
SCEnter();
if (alpd_ctx.alproto_names[alproto] == NULL)
alpd_ctx.alproto_names[alproto] = alproto_name;
SCReturn;
}
Commit Message: proto/detect: workaround dns misdetected as dcerpc
The DCERPC UDP detection would misfire on DNS with transaction
ID 0x0400. This would happen as the protocol detection engine
gives preference to pattern based detection over probing parsers for
performance reasons.
This hack/workaround fixes this specific case by still running the
probing parser if DCERPC has been detected on UDP. The probing
parser result will take precedence.
Bug #2736.
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: userauth_pubkey(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct passwd *pw = authctxt->pw;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
u_char *pkblob, *sig, have_sig;
size_t blen, slen;
int r, pktype;
int authenticated = 0;
struct sshauthopt *authopts = NULL;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
(r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
fatal("%s: parse request failed: %s", __func__, ssh_err(r));
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
verbose("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: could not parse key: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
logit("Refusing RSA key because client uses unsafe "
"signature scheme");
goto done;
}
if (auth2_key_already_used(authctxt, key)) {
logit("refusing previously-used %s key", sshkey_type(key));
goto done;
}
if (match_pattern_list(pkalg, options.pubkey_key_types, 0) != 1) {
logit("%s: key type %s not in PubkeyAcceptedKeyTypes",
__func__, sshkey_ssh_name(key));
goto done;
}
key_s = format_key(key);
if (sshkey_is_cert(key))
ca_s = format_key(key->cert->signature_key);
if (have_sig) {
debug3("%s: have %s signature for %s%s%s",
__func__, pkalg, key_s,
ca_s == NULL ? "" : " CA ",
ca_s == NULL ? "" : ca_s);
if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
(r = sshpkt_get_end(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if (ssh->compat & SSH_OLD_SESSIONID) {
if ((r = sshbuf_put(b, session_id2,
session_id2_len)) != 0)
fatal("%s: sshbuf_put session id: %s",
__func__, ssh_err(r));
} else {
if ((r = sshbuf_put_string(b, session_id2,
session_id2_len)) != 0)
fatal("%s: sshbuf_put_string session id: %s",
__func__, ssh_err(r));
}
/* reconstruct packet */
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, userstyle)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "publickey")) != 0 ||
(r = sshbuf_put_u8(b, have_sig)) != 0 ||
(r = sshbuf_put_cstring(b, pkalg) != 0) ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0)
fatal("%s: build packet failed: %s",
__func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
/* test for correct signature */
authenticated = 0;
if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b),
(ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
ssh->compat)) == 0) {
authenticated = 1;
}
sshbuf_free(b);
free(sig);
auth2_record_key(authctxt, authenticated, key);
} else {
debug("%s: test pkalg %s pkblob %s%s%s",
__func__, pkalg, key_s,
ca_s == NULL ? "" : " CA ",
ca_s == NULL ? "" : ca_s);
if ((r = sshpkt_get_end(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
/* XXX fake reply and always send PK_OK ? */
/*
* XXX this allows testing whether a user is allowed
* to login: if you happen to have a valid pubkey this
* message is sent. the message is NEVER sent at all
* if a user is not allowed to login. is this an
* issue? -markus
*/
if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
!= 0 ||
(r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
(r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
(r = sshpkt_send(ssh)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
authctxt->postponed = 1;
}
}
done:
if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
debug("%s: key options inconsistent with existing", __func__);
authenticated = 0;
}
debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg);
sshauthopt_free(authopts);
sshkey_free(key);
free(userstyle);
free(pkalg);
free(pkblob);
free(key_s);
free(ca_s);
return authenticated;
}
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt
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 struct key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
if (ctx->index_key.type == &key_type_keyring)
return ERR_PTR(-EPERM);
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
Commit Message: KEYS: add missing permission check for request_key() destination
When the request_key() syscall is not passed a destination keyring, it
links the requested key (if constructed) into the "default" request-key
keyring. This should require Write permission to the keyring. However,
there is actually no permission check.
This can be abused to add keys to any keyring to which only Search
permission is granted. This is because Search permission allows joining
the keyring. keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_SESSION_KEYRING)
then will set the default request-key keyring to the session keyring.
Then, request_key() can be used to add keys to the keyring.
Both negatively and positively instantiated keys can be added using this
method. Adding negative keys is trivial. Adding a positive key is a
bit trickier. It requires that either /sbin/request-key positively
instantiates the key, or that another thread adds the key to the process
keyring at just the right time, such that request_key() misses it
initially but then finds it in construct_alloc_key().
Fix this bug by checking for Write permission to the keyring in
construct_get_dest_keyring() when the default keyring is being used.
We don't do the permission check for non-default keyrings because that
was already done by the earlier call to lookup_user_key(). Also,
request_key_and_link() is currently passed a 'struct key *' rather than
a key_ref_t, so the "possessed" bit is unavailable.
We also don't do the permission check for the "requestor keyring", to
continue to support the use case described by commit 8bbf4976b59f
("KEYS: Alter use of key instantiation link-to-keyring argument") where
/sbin/request-key recursively calls request_key() to add keys to the
original requestor's destination keyring. (I don't know of any users
who actually do that, though...)
Fixes: 3e30148c3d52 ("[PATCH] Keys: Make request-key create an authorisation key")
Cc: <[email protected]> # v2.6.13+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-862
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::BoundFramebufferHasStencilAttachment() {
FramebufferManager::FramebufferInfo* framebuffer =
GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT);
if (framebuffer) {
return framebuffer->HasStencilAttachment();
}
if (offscreen_target_frame_buffer_.get()) {
return offscreen_target_stencil_format_ != 0 ||
offscreen_target_depth_format_ == GL_DEPTH24_STENCIL8;
}
return back_buffer_has_stencil_;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
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: PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
Commit Message:
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: _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */
uint32_t next_keylen, /* IN */
const char **key, /* OUT */
uint32_t *bson_type, /* OUT */
bool *unsupported) /* OUT */
{
const uint8_t *data;
uint32_t o;
unsigned int len;
BSON_ASSERT (iter);
*unsupported = false;
if (!iter->raw) {
*key = NULL;
*bson_type = BSON_TYPE_EOD;
return false;
}
data = iter->raw;
len = iter->len;
iter->off = iter->next_off;
iter->type = iter->off;
iter->key = iter->off + 1;
iter->d1 = 0;
iter->d2 = 0;
iter->d3 = 0;
iter->d4 = 0;
if (next_keylen == 0) {
/* iterate from start to end of NULL-terminated key string */
for (o = iter->key; o < len; o++) {
if (!data[o]) {
iter->d1 = ++o;
goto fill_data_fields;
}
}
} else {
o = iter->key + next_keylen + 1;
iter->d1 = o;
goto fill_data_fields;
}
goto mark_invalid;
fill_data_fields:
*key = bson_iter_key_unsafe (iter);
*bson_type = ITER_TYPE (iter);
switch (*bson_type) {
case BSON_TYPE_DATE_TIME:
case BSON_TYPE_DOUBLE:
case BSON_TYPE_INT64:
case BSON_TYPE_TIMESTAMP:
iter->next_off = o + 8;
break;
case BSON_TYPE_CODE:
case BSON_TYPE_SYMBOL:
case BSON_TYPE_UTF8: {
uint32_t l;
if ((o + 4) >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l > (len - (o + 4))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 4 + l;
/*
* Make sure the string length includes the NUL byte.
*/
if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) {
iter->err_off = o;
goto mark_invalid;
}
/*
* Make sure the last byte is a NUL byte.
*/
if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) {
iter->err_off = o + 4 + l - 1;
goto mark_invalid;
}
} break;
case BSON_TYPE_BINARY: {
bson_subtype_t subtype;
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 5;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l >= (len - o)) {
iter->err_off = o;
goto mark_invalid;
}
subtype = *(iter->raw + iter->d2);
if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
int32_t binary_len;
if (l < 4) {
iter->err_off = o;
goto mark_invalid;
}
/* subtype 2 has a redundant length header in the data */
memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len));
binary_len = BSON_UINT32_FROM_LE (binary_len);
if (binary_len + 4 != l) {
iter->err_off = iter->d3;
goto mark_invalid;
}
}
iter->next_off = o + 5 + l;
} break;
case BSON_TYPE_ARRAY:
case BSON_TYPE_DOCUMENT: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l > len) || (l > (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
} break;
case BSON_TYPE_OID:
iter->next_off = o + 12;
break;
case BSON_TYPE_BOOL: {
char val;
if (iter->d1 >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&val, iter->raw + iter->d1, 1);
if (val != 0x00 && val != 0x01) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_REGEX: {
bool eor = false;
bool eoo = false;
for (; o < len; o++) {
if (!data[o]) {
iter->d2 = ++o;
eor = true;
break;
}
}
if (!eor) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
for (; o < len; o++) {
if (!data[o]) {
eoo = true;
break;
}
}
if (!eoo) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_DBPOINTER: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
/* Check valid string length. l counts '\0' but not 4 bytes for itself. */
if (l == 0 || l > (len - o - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if (*(iter->raw + o + l + 3)) {
/* not null terminated */
iter->err_off = o + l + 3;
goto mark_invalid;
}
iter->d3 = o + 4 + l;
iter->next_off = o + 4 + l + 12;
} break;
case BSON_TYPE_CODEWSCOPE: {
uint32_t l;
uint32_t doclen;
if ((len < 19) || (o >= (len - 14))) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 8;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l < 14) || (l >= (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d2, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l == 0 || l >= (len - o - 4 - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if ((o + 4 + 4 + l + 4) >= iter->next_off) {
iter->err_off = o + 4;
goto mark_invalid;
}
iter->d4 = o + 4 + 4 + l;
memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen));
doclen = BSON_UINT32_FROM_LE (doclen);
if ((o + 4 + 4 + l + doclen) != iter->next_off) {
iter->err_off = o + 4 + 4 + l;
goto mark_invalid;
}
} break;
case BSON_TYPE_INT32:
iter->next_off = o + 4;
break;
case BSON_TYPE_DECIMAL128:
iter->next_off = o + 16;
break;
case BSON_TYPE_MAXKEY:
case BSON_TYPE_MINKEY:
case BSON_TYPE_NULL:
case BSON_TYPE_UNDEFINED:
iter->next_off = o;
break;
default:
*unsupported = true;
/* FALL THROUGH */
case BSON_TYPE_EOD:
iter->err_off = o;
goto mark_invalid;
}
/*
* Check to see if any of the field locations would overflow the
* current BSON buffer. If so, set the error location to the offset
* of where the field starts.
*/
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->err_off = 0;
return true;
mark_invalid:
iter->raw = NULL;
iter->len = 0;
iter->next_off = 0;
return false;
}
Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read.
As reported here: https://jira.mongodb.org/browse/CDRIVER-2819,
a heap overread occurs due a failure to correctly verify data
bounds.
In the original check, len - o returns the data left including the
sizeof(l) we just read. Instead, the comparison should check
against the data left NOT including the binary int32, i.e. just
subtype (byte*) instead of int32 subtype (byte*).
Added in test for corrupted BSON example.
CWE ID: CWE-125
Target: 1
Example 2:
Code: map_engine_get_talk_button(void)
{
return s_talk_button;
}
Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268)
* Fix integer overflow in layer_resize in map_engine.c
There's a buffer overflow bug in the function layer_resize. It allocates
a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`.
But it didn't check for integer overflow, so if x_size and y_size are
very large, it's possible that the buffer size is smaller than needed,
causing a buffer overflow later.
PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);`
* move malloc to a separate line
CWE ID: CWE-190
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 srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
{
int ret;
ret = 0;
switch (event->event) {
case IB_CM_REQ_RECEIVED:
ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
event->private_data);
break;
case IB_CM_REJ_RECEIVED:
srpt_cm_rej_recv(cm_id);
break;
case IB_CM_RTU_RECEIVED:
case IB_CM_USER_ESTABLISHED:
srpt_cm_rtu_recv(cm_id);
break;
case IB_CM_DREQ_RECEIVED:
srpt_cm_dreq_recv(cm_id);
break;
case IB_CM_DREP_RECEIVED:
srpt_cm_drep_recv(cm_id);
break;
case IB_CM_TIMEWAIT_EXIT:
srpt_cm_timewait_exit(cm_id);
break;
case IB_CM_REP_ERROR:
srpt_cm_rep_error(cm_id);
break;
case IB_CM_DREQ_ERROR:
pr_info("Received IB DREQ ERROR event.\n");
break;
case IB_CM_MRA_RECEIVED:
pr_info("Received IB MRA event\n");
break;
default:
pr_err("received unrecognized IB CM event %d\n", event->event);
break;
}
return ret;
}
Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt()
Let the target core check task existence instead of the SRP target
driver. Additionally, let the target core check the validity of the
task management request instead of the ib_srpt driver.
This patch fixes the following kernel crash:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000001
IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt]
Oops: 0002 [#1] SMP
Call Trace:
[<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt]
[<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt]
[<ffffffff8109726f>] kthread+0xcf/0xe0
[<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0
Signed-off-by: Bart Van Assche <[email protected]>
Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr")
Tested-by: Alex Estrin <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Cc: Nicholas Bellinger <[email protected]>
Cc: Sagi Grimberg <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
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 EventBindings::AttachFilteredEvent(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_EQ(2, args.Length());
CHECK(args[0]->IsString());
CHECK(args[1]->IsObject());
std::string event_name = *v8::String::Utf8Value(args[0]);
if (!context()->HasAccessOrThrowError(event_name))
return;
std::unique_ptr<base::DictionaryValue> filter;
{
std::unique_ptr<content::V8ValueConverter> converter(
content::V8ValueConverter::create());
std::unique_ptr<base::Value> filter_value(converter->FromV8Value(
v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
args.GetReturnValue().Set(static_cast<int32_t>(-1));
return;
}
filter = base::DictionaryValue::From(std::move(filter_value));
}
base::DictionaryValue* filter_weak = filter.get();
int id = g_event_filter.Get().AddEventMatcher(
event_name, ParseEventMatcher(std::move(filter)));
attached_matcher_ids_.insert(id);
std::string extension_id = context()->GetExtensionID();
if (AddFilter(event_name, extension_id, *filter_weak)) {
bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
extension_id, event_name, *filter_weak, lazy));
}
args.GetReturnValue().Set(static_cast<int32_t>(id));
}
Commit Message: Ignore filtered event if an event matcher cannot be added.
BUG=625404
Review-Url: https://codereview.chromium.org/2236133002
Cr-Commit-Position: refs/heads/master@{#411472}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int ext3_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext3_journal_start(dquot_to_inode(dquot),
EXT3_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext3_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
Commit Message: ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: [email protected]
Signed-off-by: Lars-Peter Clausen <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-20
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 ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (!skb->local_df && skb->len > mtu) {
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
dst_release(&rt->dst);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
dst_release(&rt->dst);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev));
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
kfree_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[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: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_,
proto_tree *tree, guint8 *drep _U_, char **data,
int hf_name)
{
gint len, remaining;
char *text;
if (offset % 2)
offset += 2 - (offset % 2);
/* Get remaining data in buffer as a string */
remaining = tvb_captured_length_remaining(tvb, offset);
if (remaining <= 0) {
if (data)
*data = g_strdup("");
return offset;
}
text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN);
len = (int)strlen(text);
proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text);
if (data)
*data = text;
else
g_free(text);
return offset + (len + 1) * 2;
}
Commit Message: SPOOLSS: Try to avoid an infinite loop.
Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make
sure our offset always increments in dissect_spoolss_keybuffer.
Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793
Reviewed-on: https://code.wireshark.org/review/14687
Reviewed-by: Gerald Combs <[email protected]>
Petri-Dish: Gerald Combs <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int bdev_set(struct inode *inode, void *data)
{
BDEV_I(inode)->bdev.bd_dev = *(dev_t *)data;
return 0;
}
Commit Message: ->splice_write() via ->write_iter()
iter_file_splice_write() - a ->splice_write() instance that gathers the
pipe buffers, builds a bio_vec-based iov_iter covering those and feeds
it to ->write_iter(). A bunch of simple cases coverted to that...
[AV: fixed the braino spotted by Cyrill]
Signed-off-by: Al Viro <[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: DataPipeProducerDispatcher::Deserialize(const void* data,
size_t num_bytes,
const ports::PortName* ports,
size_t num_ports,
PlatformHandle* handles,
size_t num_handles) {
if (num_ports != 1 || num_handles != 1 ||
num_bytes != sizeof(SerializedState)) {
return nullptr;
}
const SerializedState* state = static_cast<const SerializedState*>(data);
if (!state->options.capacity_num_bytes || !state->options.element_num_bytes ||
state->options.capacity_num_bytes < state->options.element_num_bytes) {
return nullptr;
}
NodeController* node_controller = Core::Get()->GetNodeController();
ports::PortRef port;
if (node_controller->node()->GetPort(ports[0], &port) != ports::OK)
return nullptr;
auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles(
std::move(handles[0]), PlatformHandle());
auto region = base::subtle::PlatformSharedMemoryRegion::Take(
std::move(region_handle),
base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe,
state->options.capacity_num_bytes,
base::UnguessableToken::Deserialize(state->buffer_guid_high,
state->buffer_guid_low));
auto ring_buffer =
base::UnsafeSharedMemoryRegion::Deserialize(std::move(region));
if (!ring_buffer.IsValid()) {
DLOG(ERROR) << "Failed to deserialize shared buffer handle.";
return nullptr;
}
scoped_refptr<DataPipeProducerDispatcher> dispatcher =
new DataPipeProducerDispatcher(node_controller, port,
std::move(ring_buffer), state->options,
state->pipe_id);
{
base::AutoLock lock(dispatcher->lock_);
dispatcher->write_offset_ = state->write_offset;
dispatcher->available_capacity_ = state->available_capacity;
dispatcher->peer_closed_ = state->flags & kFlagPeerClosed;
if (!dispatcher->InitializeNoLock())
return nullptr;
dispatcher->UpdateSignalsStateNoLock();
}
return dispatcher;
}
Commit Message: [mojo-core] Validate data pipe endpoint metadata
Ensures that we don't blindly trust specified buffer size and offset
metadata when deserializing data pipe consumer and producer handles.
Bug: 877182
Change-Id: I30f3eceafb5cee06284c2714d08357ef911d6fd9
Reviewed-on: https://chromium-review.googlesource.com/1192922
Reviewed-by: Reilly Grant <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586704}
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: xfs_attr_rmtval_set(
struct xfs_da_args *args)
{
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_bmbt_irec map;
xfs_dablk_t lblkno;
xfs_fileoff_t lfileoff = 0;
__uint8_t *src = args->value;
int blkcnt;
int valuelen;
int nmap;
int error;
int offset = 0;
trace_xfs_attr_rmtval_set(args);
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into. Because CRC enable
* attributes have headers, we can't just do a straight byte to FSB
* conversion and have to take the header space into account.
*/
blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error)
return error;
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
int committed;
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
valuelen = args->valuelen;
while (valuelen > 0) {
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT(blkcnt > 0);
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);
if (!bp)
return ENOMEM;
bp->b_ops = &xfs_attr3_rmt_buf_ops;
xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,
&valuelen, &src);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
ASSERT(valuelen == 0);
return 0;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19
Target: 1
Example 2:
Code: void WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
WebContentsImpl* inner_web_contents) {
DCHECK(std::find(inner_web_contents_.begin(), inner_web_contents_.end(),
inner_web_contents) != inner_web_contents_.end());
inner_web_contents_.erase(
std::remove(inner_web_contents_.begin(), inner_web_contents_.end(),
inner_web_contents),
inner_web_contents_.end());
}
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: void CrosLibrary::TestApi::SetUpdateLibrary(
UpdateLibrary* library, bool own) {
library_->update_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
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: krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID:
Target: 1
Example 2:
Code: static __latent_entropy void tasklet_action(struct softirq_action *a)
{
tasklet_action_common(a, this_cpu_ptr(&tasklet_vec), TASKLET_SOFTIRQ);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
WebContentsImpl* inner_web_contents) {
inner_web_contents_.push_back(inner_web_contents);
}
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
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_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
it->templates, opt, ctx);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
if (*pval) {
/* Free up and zero CHOICE value if initialised */
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
tt = it->templates + i;
pchptr = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchptr, tt);
asn1_set_choice_selector(pval, -1, it);
}
} else if (!ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* CHOICE type, try each possibility in turn */
p = *in;
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
pchptr = asn1_get_field_ptr(pval, tt);
/*
* We mark field as OPTIONAL so its absence can be recognised.
*/
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Free up and zero any ADB found */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
if (tt->flags & ASN1_TFLG_ADB_MASK) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
}
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
pseqval = asn1_get_field_ptr(pval, seqtt);
/* Have we ran out of data? */
if (!len)
break;
q = p;
if (asn1_check_eoc(&p, len)) {
if (!seq_eoc) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
seq_eoc = 0;
q = p;
break;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
default:
return 0;
}
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
err:
ASN1_item_ex_free(pval, it);
if (errtt)
ERR_add_error_data(4, "Field=", errtt->field_name,
", Type=", it->sname);
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: void inet_csk_destroy_sock(struct sock *sk)
{
WARN_ON(sk->sk_state != TCP_CLOSE);
WARN_ON(!sock_flag(sk, SOCK_DEAD));
/* It cannot be in hash table! */
WARN_ON(!sk_unhashed(sk));
/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
sk->sk_prot->destroy(sk);
sk_stream_kill_queues(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
percpu_counter_dec(sk->sk_prot->orphan_count);
sock_put(sk);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AssertObserverCount(int added_count, int removed_count,
int changed_count) {
ASSERT_EQ(added_count, added_count_);
ASSERT_EQ(removed_count, removed_count_);
ASSERT_EQ(changed_count, changed_count_);
}
Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods.
BUG=None
TEST=None
[email protected]
Review URL: http://codereview.chromium.org/7046093
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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 f_parser (lua_State *L, void *ud) {
int i;
Proto *tf;
Closure *cl;
struct SParser *p = cast(struct SParser *, ud);
int c = luaZ_lookahead(p->z);
luaC_checkGC(L);
tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,
&p->buff, p->name);
cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
cl->l.p = tf;
for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */
cl->l.upvals[i] = luaF_newupval(L);
setclvalue(L, L->top, cl);
incr_top(L);
}
Commit Message: disable loading lua bytecode
CWE ID: CWE-17
Target: 1
Example 2:
Code: static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
int rc = WRC_Continue;
struct CCurHint *pHint = pWalker->u.pCCurHint;
if( pExpr->op==TK_COLUMN ){
if( pExpr->iTable!=pHint->iTabCur ){
Vdbe *v = pWalker->pParse->pVdbe;
int reg = ++pWalker->pParse->nMem; /* Register for column value */
sqlite3ExprCodeGetColumnOfTable(
v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
);
pExpr->op = TK_REGISTER;
pExpr->iTable = reg;
}else if( pHint->pIdx!=0 ){
pExpr->iTable = pHint->iIdxCur;
pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
assert( pExpr->iColumn>=0 );
}
}else if( pExpr->op==TK_AGG_FUNCTION ){
/* An aggregate function in the WHERE clause of a query means this must
** be a correlated sub-query, and expression pExpr is an aggregate from
** the parent context. Do not walk the function arguments in this case.
**
** todo: It should be possible to replace this node with a TK_REGISTER
** expression, as the result of the expression must be stored in a
** register at this point. The same holds for TK_AGG_COLUMN nodes. */
rc = WRC_Prune;
}
return rc;
}
Commit Message: sqlite: safely move pointer values through SQL.
This lands https://www.sqlite.org/src/timeline?c=d6a44b35 in
third_party/sqlite/src/ and
third_party/sqlite/patches/0013-Add-new-interfaces-sqlite3_bind_pointer-sqlite3_resu.patch
and re-generates third_party/sqlite/amalgamation/* using the script at
third_party/sqlite/google_generate_amalgamation.sh.
The CL also adds a layout test that verifies the patch works as intended.
BUG=742407
Change-Id: I2e1a457459cd2e975e6241b630e7b79c82545981
Reviewed-on: https://chromium-review.googlesource.com/572976
Reviewed-by: Chris Mumford <[email protected]>
Commit-Queue: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#487275}
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 FrameBuffer::Destroy() {
if (id_ != 0) {
ScopedGLErrorSuppressor suppressor(decoder_);
glDeleteFramebuffersEXT(1, &id_);
id_ = 0;
}
}
Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0."""
TEST=none
BUG=95625
[email protected]
Review URL: http://codereview.chromium.org/7796016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert5(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"));
e* (toe(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert5();
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: partition_modify_completed_cb (DBusGMethodInvocation *context,
Device *device,
gboolean job_was_cancelled,
int status,
const char *stderr,
const char *stdout,
gpointer user_data)
{
ModifyPartitionData *data = user_data;
/* poke the kernel so we can reread the data */
device_generate_kernel_change_event (data->enclosing_device);
device_generate_kernel_change_event (data->device);
if (WEXITSTATUS (status) == 0 && !job_was_cancelled)
{
/* update local copy, don't wait for the kernel */
device_set_partition_type (device, data->type);
device_set_partition_label (device, data->label);
device_set_partition_flags (device, data->flags);
drain_pending_changes (device, FALSE);
dbus_g_method_return (context);
}
else
{
if (job_was_cancelled)
{
throw_error (context, ERROR_CANCELLED, "Job was cancelled");
}
else
{
throw_error (context,
ERROR_FAILED,
"Error modifying partition: helper exited with exit code %d: %s",
WEXITSTATUS (status),
stderr);
}
}
}
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: status_t SoftVPXEncoder::initEncoder() {
vpx_codec_err_t codec_return;
mCodecContext = new vpx_codec_ctx_t;
mCodecConfiguration = new vpx_codec_enc_cfg_t;
mCodecInterface = vpx_codec_vp8_cx();
if (mCodecInterface == NULL) {
return UNKNOWN_ERROR;
}
ALOGD("VP8: initEncoder. BRMode: %u. TSLayers: %zu. KF: %u. QP: %u - %u",
(uint32_t)mBitrateControlMode, mTemporalLayers, mKeyFrameInterval,
mMinQuantizer, mMaxQuantizer);
codec_return = vpx_codec_enc_config_default(mCodecInterface,
mCodecConfiguration,
0); // Codec specific flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error populating default configuration for vpx encoder.");
return UNKNOWN_ERROR;
}
mCodecConfiguration->g_w = mWidth;
mCodecConfiguration->g_h = mHeight;
mCodecConfiguration->g_threads = GetCPUCoreCount();
mCodecConfiguration->g_error_resilient = mErrorResilience;
switch (mLevel) {
case OMX_VIDEO_VP8Level_Version0:
mCodecConfiguration->g_profile = 0;
break;
case OMX_VIDEO_VP8Level_Version1:
mCodecConfiguration->g_profile = 1;
break;
case OMX_VIDEO_VP8Level_Version2:
mCodecConfiguration->g_profile = 2;
break;
case OMX_VIDEO_VP8Level_Version3:
mCodecConfiguration->g_profile = 3;
break;
default:
mCodecConfiguration->g_profile = 0;
}
mCodecConfiguration->g_timebase.num = 1;
mCodecConfiguration->g_timebase.den = 1000000;
mCodecConfiguration->rc_target_bitrate = (mBitrate + 500) / 1000;
mCodecConfiguration->rc_end_usage = mBitrateControlMode;
mCodecConfiguration->rc_dropframe_thresh = 0;
if (mBitrateControlMode == VPX_CBR) {
mCodecConfiguration->rc_resize_allowed = 0;
mCodecConfiguration->g_pass = VPX_RC_ONE_PASS;
mCodecConfiguration->rc_undershoot_pct = 100;
mCodecConfiguration->rc_overshoot_pct = 15;
mCodecConfiguration->rc_buf_initial_sz = 500;
mCodecConfiguration->rc_buf_optimal_sz = 600;
mCodecConfiguration->rc_buf_sz = 1000;
mCodecConfiguration->g_error_resilient = 1;
mCodecConfiguration->g_lag_in_frames = 0;
mCodecConfiguration->kf_max_dist = 3000;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
switch (mTemporalLayers) {
case 0:
{
mTemporalPatternLength = 0;
break;
}
case 1:
{
mCodecConfiguration->ts_number_layers = 1;
mCodecConfiguration->ts_rate_decimator[0] = 1;
mCodecConfiguration->ts_periodicity = 1;
mCodecConfiguration->ts_layer_id[0] = 0;
mTemporalPattern[0] = kTemporalUpdateLastRefAll;
mTemporalPatternLength = 1;
break;
}
case 2:
{
mCodecConfiguration->ts_number_layers = 2;
mCodecConfiguration->ts_rate_decimator[0] = 2;
mCodecConfiguration->ts_rate_decimator[1] = 1;
mCodecConfiguration->ts_periodicity = 2;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 1;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[2] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[3] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[6] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
case 3:
{
mCodecConfiguration->ts_number_layers = 3;
mCodecConfiguration->ts_rate_decimator[0] = 4;
mCodecConfiguration->ts_rate_decimator[1] = 2;
mCodecConfiguration->ts_rate_decimator[2] = 1;
mCodecConfiguration->ts_periodicity = 4;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 2;
mCodecConfiguration->ts_layer_id[2] = 1;
mCodecConfiguration->ts_layer_id[3] = 2;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateNoneNoRefGoldenRefAltRef;
mTemporalPattern[2] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[3] = kTemporalUpdateNone;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateNone;
mTemporalPattern[6] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
default:
{
ALOGE("Wrong number of temporal layers %zu", mTemporalLayers);
return UNKNOWN_ERROR;
}
}
for (size_t i = 0; i < mCodecConfiguration->ts_number_layers; i++) {
mCodecConfiguration->ts_target_bitrate[i] =
mCodecConfiguration->rc_target_bitrate *
mTemporalLayerBitrateRatio[i] / 100;
}
if (mKeyFrameInterval > 0) {
mCodecConfiguration->kf_max_dist = mKeyFrameInterval;
mCodecConfiguration->kf_min_dist = mKeyFrameInterval;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
if (mMinQuantizer > 0) {
mCodecConfiguration->rc_min_quantizer = mMinQuantizer;
}
if (mMaxQuantizer > 0) {
mCodecConfiguration->rc_max_quantizer = mMaxQuantizer;
}
codec_return = vpx_codec_enc_init(mCodecContext,
mCodecInterface,
mCodecConfiguration,
0); // flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error initializing vpx encoder");
return UNKNOWN_ERROR;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_TOKEN_PARTITIONS,
mDCTPartitions);
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting dct partitions for vpx encoder.");
return UNKNOWN_ERROR;
}
if (mBitrateControlMode == VPX_CBR) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_STATIC_THRESHOLD,
1);
if (codec_return == VPX_CODEC_OK) {
uint32_t rc_max_intra_target =
mCodecConfiguration->rc_buf_optimal_sz * (mFramerate >> 17) / 10;
if (rc_max_intra_target < 300) {
rc_max_intra_target = 300;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_MAX_INTRA_BITRATE_PCT,
rc_max_intra_target);
}
if (codec_return == VPX_CODEC_OK) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_CPUUSED,
-8);
}
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting cbr parameters for vpx encoder.");
return UNKNOWN_ERROR;
}
}
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mConversionBuffer);
mConversionBuffer = (uint8_t *)malloc(mWidth * mHeight * 3 / 2);
if (mConversionBuffer == NULL) {
ALOGE("Allocating conversion buffer failed.");
return UNKNOWN_ERROR;
}
}
return OK;
}
Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder.
Bug: 25812794
Change-Id: I96dc74734380d462583f6efa33d09946f9532809
(cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba)
(cherry picked from commit 0462975291796e414891e04bcec9da993914e458)
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void skcipher_release(void *private)
{
crypto_free_skcipher(private);
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: void kgdb_arch_set_pc(struct pt_regs *regs, unsigned long ip)
{
regs->ip = ip;
}
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: 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 DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p,
uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto)
{
switch (proto) {
case DECODE_TUNNEL_PPP:
return DecodePPP(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV4:
return DecodeIPV4(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV6:
return DecodeIPV6(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_VLAN:
return DecodeVLAN(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ETHERNET:
return DecodeEthernet(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ERSPAN:
return DecodeERSPAN(tv, dtv, p, pkt, len, pq);
default:
SCLogInfo("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto);
break;
}
return TM_ECODE_OK;
}
Commit Message: teredo: be stricter on what to consider valid teredo
Invalid Teredo can lead to valid DNS traffic (or other UDP traffic)
being misdetected as Teredo. This leads to false negatives in the
UDP payload inspection.
Make the teredo code only consider a packet teredo if the encapsulated
data was decoded without any 'invalid' events being set.
Bug #2736.
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void handle_data_packet(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
struct mt_mactelnet_control_hdr cpkt;
struct mt_packet pdata;
unsigned char *data = pkthdr->data;
unsigned int act_size = 0;
int got_user_packet = 0;
int got_pass_packet = 0;
int got_width_packet = 0;
int got_height_packet = 0;
int success;
/* Parse first control packet */
success = parse_control_packet(data, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {
int plen,i;
if (!curconn->have_pass_salt) {
for (i = 0; i < 16; ++i) {
curconn->pass_salt[i] = rand() % 256;
}
curconn->have_pass_salt = 1;
memset(curconn->trypassword, 0, sizeof(curconn->trypassword));
}
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PASSSALT, (curconn->pass_salt), 16);
curconn->outcounter += plen;
send_udp(curconn, &pdata);
/* Don't change the username after the state is active */
} else if (cpkt.cptype == MT_CPTYPE_USERNAME && curconn->state != STATE_ACTIVE) {
memcpy(curconn->username, cpkt.data, act_size = (cpkt.length > MT_MNDP_MAX_STRING_SIZE - 1 ? MT_MNDP_MAX_STRING_SIZE - 1 : cpkt.length));
curconn->username[act_size] = 0;
got_user_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH && cpkt.length >= 2) {
unsigned short width;
memcpy(&width, cpkt.data, 2);
curconn->terminal_width = le16toh(width);
got_width_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT && cpkt.length >= 2) {
unsigned short height;
memcpy(&height, cpkt.data, 2);
curconn->terminal_height = le16toh(height);
got_height_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {
memcpy(curconn->terminal_type, cpkt.data, act_size = (cpkt.length > 30 - 1 ? 30 - 1 : cpkt.length));
curconn->terminal_type[act_size] = 0;
} else if (cpkt.cptype == MT_CPTYPE_PASSWORD) {
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(curconn->trypassword, 17);
#endif
memcpy(curconn->trypassword, cpkt.data, 17);
got_pass_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
/* relay data from client to shell */
if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
write(curconn->ptsfd, cpkt.data, cpkt.length);
}
} else {
syslog(LOG_WARNING, _("(%d) Unhandeled control packet type: %d"), curconn->seskey, cpkt.cptype);
}
/* Parse next control packet */
success = parse_control_packet(NULL, 0, &cpkt);
}
if (got_user_packet && got_pass_packet) {
user_login(curconn, pkthdr);
}
if (curconn->state == STATE_ACTIVE && (got_width_packet || got_height_packet)) {
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
Commit Message: Merge pull request #20 from eyalitki/master
2nd round security fixes from eyalitki
CWE ID: CWE-119
Target: 1
Example 2:
Code: int do_sigaction(int sig, struct k_sigaction *act, struct k_sigaction *oact)
{
struct task_struct *t = current;
struct k_sigaction *k;
sigset_t mask;
if (!valid_signal(sig) || sig < 1 || (act && sig_kernel_only(sig)))
return -EINVAL;
k = &t->sighand->action[sig-1];
spin_lock_irq(¤t->sighand->siglock);
if (oact)
*oact = *k;
if (act) {
sigdelsetmask(&act->sa.sa_mask,
sigmask(SIGKILL) | sigmask(SIGSTOP));
*k = *act;
/*
* POSIX 3.3.1.3:
* "Setting a signal action to SIG_IGN for a signal that is
* pending shall cause the pending signal to be discarded,
* whether or not it is blocked."
*
* "Setting a signal action to SIG_DFL for a signal that is
* pending and whose default action is to ignore the signal
* (for example, SIGCHLD), shall cause the pending signal to
* be discarded, whether or not it is blocked"
*/
if (sig_handler_ignored(sig_handler(t, sig), sig)) {
sigemptyset(&mask);
sigaddset(&mask, sig);
rm_from_queue_full(&mask, &t->signal->shared_pending);
do {
rm_from_queue_full(&mask, &t->pending);
t = next_thread(t);
} while (t != current);
}
}
spin_unlock_irq(¤t->sighand->siglock);
return 0;
}
Commit Message: kernel/signal.c: stop info leak via the tkill and the tgkill syscalls
This fixes a kernel memory contents leak via the tkill and tgkill syscalls
for compat processes.
This is visible in the siginfo_t->_sifields._rt.si_sigval.sival_ptr field
when handling signals delivered from tkill.
The place of the infoleak:
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
...
put_user_ex(ptr_to_compat(from->si_ptr), &to->si_ptr);
...
}
Signed-off-by: Emese Revfy <[email protected]>
Reviewed-by: PaX Team <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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 Textfield::UseDefaultTextColor() {
use_default_text_color_ = true;
SetColor(GetTextColor());
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr,
unsigned long shmlba)
{
struct shmid_kernel *shp;
unsigned long addr;
unsigned long size;
struct file *file;
int err;
unsigned long flags;
unsigned long prot;
int acc_mode;
struct ipc_namespace *ns;
struct shm_file_data *sfd;
struct path path;
fmode_t f_mode;
unsigned long populate = 0;
err = -EINVAL;
if (shmid < 0)
goto out;
else if ((addr = (ulong)shmaddr)) {
if (addr & (shmlba - 1)) {
if (shmflg & SHM_RND)
addr &= ~(shmlba - 1); /* round down */
else
#ifndef __ARCH_FORCE_SHMLBA
if (addr & ~PAGE_MASK)
#endif
goto out;
}
flags = MAP_SHARED | MAP_FIXED;
} else {
if ((shmflg & SHM_REMAP))
goto out;
flags = MAP_SHARED;
}
if (shmflg & SHM_RDONLY) {
prot = PROT_READ;
acc_mode = S_IRUGO;
f_mode = FMODE_READ;
} else {
prot = PROT_READ | PROT_WRITE;
acc_mode = S_IRUGO | S_IWUGO;
f_mode = FMODE_READ | FMODE_WRITE;
}
if (shmflg & SHM_EXEC) {
prot |= PROT_EXEC;
acc_mode |= S_IXUGO;
}
/*
* We cannot rely on the fs check since SYSV IPC does have an
* additional creator id...
*/
ns = current->nsproxy->ipc_ns;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, acc_mode))
goto out_unlock;
err = security_shm_shmat(shp, shmaddr, shmflg);
if (err)
goto out_unlock;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
ipc_unlock_object(&shp->shm_perm);
err = -EIDRM;
goto out_unlock;
}
path = shp->shm_file->f_path;
path_get(&path);
shp->shm_nattch++;
size = i_size_read(d_inode(path.dentry));
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
err = -ENOMEM;
sfd = kzalloc(sizeof(*sfd), GFP_KERNEL);
if (!sfd) {
path_put(&path);
goto out_nattch;
}
file = alloc_file(&path, f_mode,
is_file_hugepages(shp->shm_file) ?
&shm_file_operations_huge :
&shm_file_operations);
err = PTR_ERR(file);
if (IS_ERR(file)) {
kfree(sfd);
path_put(&path);
goto out_nattch;
}
file->private_data = sfd;
file->f_mapping = shp->shm_file->f_mapping;
sfd->id = shp->shm_perm.id;
sfd->ns = get_ipc_ns(ns);
sfd->file = shp->shm_file;
sfd->vm_ops = NULL;
err = security_mmap_file(file, prot, flags);
if (err)
goto out_fput;
if (down_write_killable(¤t->mm->mmap_sem)) {
err = -EINTR;
goto out_fput;
}
if (addr && !(shmflg & SHM_REMAP)) {
err = -EINVAL;
if (addr + size < addr)
goto invalid;
if (find_vma_intersection(current->mm, addr, addr + size))
goto invalid;
}
addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);
*raddr = addr;
err = 0;
if (IS_ERR_VALUE(addr))
err = (long)addr;
invalid:
up_write(¤t->mm->mmap_sem);
if (populate)
mm_populate(addr, populate);
out_fput:
fput(file);
out_nattch:
down_write(&shm_ids(ns).rwsem);
shp = shm_lock(ns, shmid);
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
return err;
out_unlock:
rcu_read_unlock();
out:
return err;
}
Commit Message: ipc/shm: Fix shmat mmap nil-page protection
The issue is described here, with a nice testcase:
https://bugzilla.kernel.org/show_bug.cgi?id=192931
The problem is that shmat() calls do_mmap_pgoff() with MAP_FIXED, and the
address rounded down to 0. For the regular mmap case, the protection
mentioned above is that the kernel gets to generate the address --
arch_get_unmapped_area() will always check for MAP_FIXED and return that
address. So by the time we do security_mmap_addr(0) things get funky for
shmat().
The testcase itself shows that while a regular user crashes, root will not
have a problem attaching a nil-page. There are two possible fixes to
this. The first, and which this patch does, is to simply allow root to
crash as well -- this is also regular mmap behavior, ie when hacking up
the testcase and adding mmap(... |MAP_FIXED). While this approach is the
safer option, the second alternative is to ignore SHM_RND if the rounded
address is 0, thus only having MAP_SHARED flags. This makes the behavior
of shmat() identical to the mmap() case. The downside of this is
obviously user visible, but does make sense in that it maintains semantics
after the round-down wrt 0 address and mmap.
Passes shm related ltp tests.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Davidlohr Bueso <[email protected]>
Reported-by: Gareth Evans <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void correctstack (lua_State *L, TValue *oldstack) {
CallInfo *ci;
GCObject *up;
L->top = (L->top - oldstack) + L->stack;
for (up = L->openupval; up != NULL; up = up->gch.next)
gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
for (ci = L->base_ci; ci <= L->ci; ci++) {
ci->top = (ci->top - oldstack) + L->stack;
ci->base = (ci->base - oldstack) + L->stack;
ci->func = (ci->func - oldstack) + L->stack;
}
L->base = (L->base - oldstack) + L->stack;
}
Commit Message: disable loading lua bytecode
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 WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 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: void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
jas_seqent_t maxval)
{
int i;
int j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
int rowstep;
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) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190
Target: 1
Example 2:
Code: void nlmsg_set_dst(struct nl_msg *msg, struct sockaddr_nl *addr)
{
memcpy(&msg->nm_dst, addr, sizeof(*addr));
}
Commit Message:
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 Document::ActiveChainNodeDetached(Element& element) {
if (active_element_ && element == active_element_) {
active_element_ =
SkipDisplayNoneAncestorsOrReturnNullIfFlatTreeIsDirty(element);
}
}
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: void impeg2d_dec_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254
Target: 1
Example 2:
Code: interpret_long_date(const u_char *p)
{
double d;
time_t ret;
/* this gives us seconds since jan 1st 1601 (approx) */
d = (EXTRACT_LE_32BITS(p + 4) * 256.0 + p[3]) * (1.0e-7 * (1 << 24));
/* now adjust by 369 years to make the secs since 1970 */
d -= 369.0 * 365.25 * 24 * 60 * 60;
/* and a fudge factor as we got it wrong by a few days */
d += (3 * 24 * 60 * 60 + 6 * 60 * 60 + 2);
if (d < 0)
return(0);
ret = (time_t)d;
return(ret);
}
Commit Message: CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len().
After we advance the pointer by the length value in the buffer, make
sure it points to something in the captured data.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
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: SampleTable::~SampleTable() {
delete[] mSampleToChunkEntries;
mSampleToChunkEntries = NULL;
delete[] mSyncSamples;
mSyncSamples = NULL;
delete mCompositionDeltaLookup;
mCompositionDeltaLookup = NULL;
delete[] mCompositionTimeDeltaEntries;
mCompositionTimeDeltaEntries = NULL;
delete[] mSampleTimeEntries;
mSampleTimeEntries = NULL;
delete[] mTimeToSample;
mTimeToSample = NULL;
delete mSampleIterator;
mSampleIterator = NULL;
}
Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release
Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d
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 MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) 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);
scene=0;
debug=IsEventLogging();
(void) debug;
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)
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;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
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;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
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) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
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_ORIENTATION,ORIENTATION_TOPLEFT);
(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);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
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);
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;
if (image->colorspace == YCbCrColorspace)
(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:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_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.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_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_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
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) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
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))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(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);
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++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
Commit Message: Fix TIFF divide by zero (bug report from Donghai Zhu)
CWE ID: CWE-369
Target: 1
Example 2:
Code: raptor_libxml_fatal_error(void* user_data, const char *msg, ...)
{
va_list args;
va_start(args, msg);
raptor_libxml_error_common(user_data, msg, args, xml_fatal_error_prefix, 1);
va_end(args);
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
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 LaunchServiceProcessControl(bool wait) {
ServiceProcessControl::GetInstance()->Launch(
base::Bind(&ServiceProcessControlBrowserTest::ProcessControlLaunched,
base::Unretained(this)),
base::Bind(
&ServiceProcessControlBrowserTest::ProcessControlLaunchFailed,
base::Unretained(this)));
if (wait)
content::RunMessageLoop();
}
Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated().
Bug: 844016
Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0
Reviewed-on: https://chromium-review.googlesource.com/1126576
Commit-Queue: Wez <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573131}
CWE ID: CWE-94
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 bnep_net_setup(struct net_device *dev)
{
memset(dev->broadcast, 0xff, ETH_ALEN);
dev->addr_len = ETH_ALEN;
ether_setup(dev);
dev->netdev_ops = &bnep_netdev_ops;
dev->watchdog_timeo = HZ * 2;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Browser::EnumerateDirectory(WebContents* web_contents,
int request_id,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
}
Commit Message: Don't focus the location bar for NTP navigations in non-selected tabs.
BUG=677716
TEST=See bug for repro steps.
Review-Url: https://codereview.chromium.org/2624373002
Cr-Commit-Position: refs/heads/master@{#443338}
CWE ID:
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 zend_throw_exception_internal(zval *exception TSRMLS_DC) /* {{{ */
{
#ifdef HAVE_DTRACE
if (DTRACE_EXCEPTION_THROWN_ENABLED()) {
const char *classname;
zend_uint name_len;
if (exception != NULL) {
zend_get_object_classname(exception, &classname, &name_len TSRMLS_CC);
DTRACE_EXCEPTION_THROWN((char *)classname);
} else {
DTRACE_EXCEPTION_THROWN(NULL);
}
}
#endif /* HAVE_DTRACE */
if (exception != NULL) {
zval *previous = EG(exception);
zend_exception_set_previous(exception, EG(exception) TSRMLS_CC);
EG(exception) = exception;
if (previous) {
return;
}
}
if (!EG(current_execute_data)) {
if(EG(exception)) {
zend_exception_error(EG(exception), E_ERROR TSRMLS_CC);
}
zend_error(E_ERROR, "Exception thrown without a stack frame");
}
if (zend_throw_exception_hook) {
zend_throw_exception_hook(exception TSRMLS_CC);
}
if (EG(current_execute_data)->opline == NULL ||
(EG(current_execute_data)->opline+1)->opcode == ZEND_HANDLE_EXCEPTION) {
/* no need to rethrow the exception */
return;
}
EG(opline_before_exception) = EG(current_execute_data)->opline;
EG(current_execute_data)->opline = EG(exception_op);
}
/* }}} */
Commit Message:
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: int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)
{
int res, bytes, i, indexes, index_bytes, ids;
long long *index, start, end;
struct squashfs_xattr_table id_table;
TRACE("read_xattrs_from_disk\n");
if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)
return SQUASHFS_INVALID_BLK;
/*
* Read xattr id table, containing start of xattr metadata and the
* number of xattrs in the file system
*/
res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),
&id_table);
if(res == 0)
return 0;
SQUASHFS_INSWAP_XATTR_TABLE(&id_table);
if(flag) {
/*
* id_table.xattr_table_start stores the start of the compressed xattr
* * metadata blocks. This by definition is also the end of the previous
* filesystem table - the id lookup table.
*/
*table_start = id_table.xattr_table_start;
return id_table.xattr_ids;
}
/*
* Allocate and read the index to the xattr id table metadata
* blocks
*/
ids = id_table.xattr_ids;
xattr_table_start = id_table.xattr_table_start;
index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids);
indexes = SQUASHFS_XATTR_BLOCKS(ids);
index = malloc(index_bytes);
if(index == NULL)
MEM_ERROR();
res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),
index_bytes, index);
if(res ==0)
goto failed1;
SQUASHFS_INSWAP_LONG_LONGS(index, indexes);
/*
* Allocate enough space for the uncompressed xattr id table, and
* read and decompress it
*/
bytes = SQUASHFS_XATTR_BYTES(ids);
xattr_ids = malloc(bytes);
if(xattr_ids == NULL)
MEM_ERROR();
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
int length = read_block(fd, index[i], NULL, expected,
((unsigned char *) xattr_ids) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr id table block %d, from 0x%llx, length "
"%d\n", i, index[i], length);
if(length == 0) {
ERROR("Failed to read xattr id table block %d, "
"from 0x%llx, length %d\n", i, index[i],
length);
goto failed2;
}
}
/*
* Read and decompress the xattr metadata
*
* Note the first xattr id table metadata block is immediately after
* the last xattr metadata block, so we can use index[0] to work out
* the end of the xattr metadata
*/
start = xattr_table_start;
end = index[0];
for(i = 0; start < end; i++) {
int length;
xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);
if(xattrs == NULL)
MEM_ERROR();
/* store mapping from location of compressed block in fs ->
* location of uncompressed block in memory */
save_xattr_block(start, i * SQUASHFS_METADATA_SIZE);
length = read_block(fd, start, &start, 0,
((unsigned char *) xattrs) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr block %d, length %d\n", i, length);
if(length == 0) {
ERROR("Failed to read xattr block %d\n", i);
goto failed3;
}
/*
* If this is not the last metadata block in the xattr metadata
* then it should be SQUASHFS_METADATA_SIZE in size.
* Note, we can't use expected in read_block() above for this
* because we don't know if this is the last block until
* after reading.
*/
if(start != end && length != SQUASHFS_METADATA_SIZE) {
ERROR("Xattr block %d should be %d bytes in length, "
"it is %d bytes\n", i, SQUASHFS_METADATA_SIZE,
length);
goto failed3;
}
}
/* swap if necessary the xattr id entries */
for(i = 0; i < ids; i++)
SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);
free(index);
return ids;
failed3:
free(xattrs);
failed2:
free(xattr_ids);
failed1:
free(index);
return 0;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190
Target: 1
Example 2:
Code: static long madvise_dontneed(struct vm_area_struct * vma,
struct vm_area_struct ** prev,
unsigned long start, unsigned long end)
{
*prev = vma;
if (vma->vm_flags & (VM_LOCKED|VM_HUGETLB|VM_PFNMAP))
return -EINVAL;
if (unlikely(vma->vm_flags & VM_NONLINEAR)) {
struct zap_details details = {
.nonlinear_vma = vma,
.last_index = ULONG_MAX,
};
zap_page_range(vma, start, end - start, &details);
} else
zap_page_range(vma, start, end - start, NULL);
return 0;
}
Commit Message: mm: Hold a file reference in madvise_remove
Otherwise the code races with munmap (causing a use-after-free
of the vma) or with close (causing a use-after-free of the struct
file).
The bug was introduced by commit 90ed52ebe481 ("[PATCH] holepunch: fix
mmap_sem i_mutex deadlock")
Cc: Hugh Dickins <[email protected]>
Cc: Miklos Szeredi <[email protected]>
Cc: Badari Pulavarty <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 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 RenderWidgetHostViewGtk::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, true, 0);
}
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: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
if (insn_bitness == 32) {
/* Relevant for 32-bit RSH: Information can propagate towards
* LSB, so it isn't sufficient to only truncate the output to
* 32 bits.
*/
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: void WallpaperManager::Open() {
if (wallpaper_manager_util::ShouldUseAndroidWallpapersApp(
ProfileHelper::Get()->GetProfileByUser(
user_manager::UserManager::Get()->GetActiveUser())) &&
!ash_util::IsRunningInMash()) {
activation_client_observer_.Add(ash::Shell::Get()->activation_client());
}
wallpaper_manager_util::OpenWallpaperManager();
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
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: nf_nat_redirect_ipv4(struct sk_buff *skb,
const struct nf_nat_ipv4_multi_range_compat *mr,
unsigned int hooknum)
{
struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
__be32 newdst;
struct nf_nat_range newrange;
NF_CT_ASSERT(hooknum == NF_INET_PRE_ROUTING ||
hooknum == NF_INET_LOCAL_OUT);
ct = nf_ct_get(skb, &ctinfo);
NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED));
/* Local packets: make them go to loopback */
if (hooknum == NF_INET_LOCAL_OUT) {
newdst = htonl(0x7F000001);
} else {
struct in_device *indev;
struct in_ifaddr *ifa;
newdst = 0;
rcu_read_lock();
indev = __in_dev_get_rcu(skb->dev);
if (indev != NULL) {
ifa = indev->ifa_list;
newdst = ifa->ifa_local;
}
rcu_read_unlock();
if (!newdst)
return NF_DROP;
}
/* Transfer from original range. */
memset(&newrange.min_addr, 0, sizeof(newrange.min_addr));
memset(&newrange.max_addr, 0, sizeof(newrange.max_addr));
newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS;
newrange.min_addr.ip = newdst;
newrange.max_addr.ip = newdst;
newrange.min_proto = mr->range[0].min;
newrange.max_proto = mr->range[0].max;
/* Hand modified range to generic setup. */
return nf_nat_setup_info(ct, &newrange, NF_NAT_MANIP_DST);
}
Commit Message: netfilter: nf_nat_redirect: add missing NULL pointer check
Commit 8b13eddfdf04cbfa561725cfc42d6868fe896f56 ("netfilter: refactor NAT
redirect IPv4 to use it from nf_tables") has introduced a trivial logic
change which can result in the following crash.
BUG: unable to handle kernel NULL pointer dereference at 0000000000000030
IP: [<ffffffffa033002d>] nf_nat_redirect_ipv4+0x2d/0xa0 [nf_nat_redirect]
PGD 3ba662067 PUD 3ba661067 PMD 0
Oops: 0000 [#1] SMP
Modules linked in: ipv6(E) xt_REDIRECT(E) nf_nat_redirect(E) xt_tcpudp(E) iptable_nat(E) nf_conntrack_ipv4(E) nf_defrag_ipv4(E) nf_nat_ipv4(E) nf_nat(E) nf_conntrack(E) ip_tables(E) x_tables(E) binfmt_misc(E) xfs(E) libcrc32c(E) evbug(E) evdev(E) psmouse(E) i2c_piix4(E) i2c_core(E) acpi_cpufreq(E) button(E) ext4(E) crc16(E) jbd2(E) mbcache(E) dm_mirror(E) dm_region_hash(E) dm_log(E) dm_mod(E)
CPU: 0 PID: 2536 Comm: ip Tainted: G E 4.1.7-15.23.amzn1.x86_64 #1
Hardware name: Xen HVM domU, BIOS 4.2.amazon 05/06/2015
task: ffff8800eb438000 ti: ffff8803ba664000 task.ti: ffff8803ba664000
[...]
Call Trace:
<IRQ>
[<ffffffffa0334065>] redirect_tg4+0x15/0x20 [xt_REDIRECT]
[<ffffffffa02e2e99>] ipt_do_table+0x2b9/0x5e1 [ip_tables]
[<ffffffffa0328045>] iptable_nat_do_chain+0x25/0x30 [iptable_nat]
[<ffffffffa031777d>] nf_nat_ipv4_fn+0x13d/0x1f0 [nf_nat_ipv4]
[<ffffffffa0328020>] ? iptable_nat_ipv4_fn+0x20/0x20 [iptable_nat]
[<ffffffffa031785e>] nf_nat_ipv4_in+0x2e/0x90 [nf_nat_ipv4]
[<ffffffffa03280a5>] iptable_nat_ipv4_in+0x15/0x20 [iptable_nat]
[<ffffffff81449137>] nf_iterate+0x57/0x80
[<ffffffff814491f7>] nf_hook_slow+0x97/0x100
[<ffffffff814504d4>] ip_rcv+0x314/0x400
unsigned int
nf_nat_redirect_ipv4(struct sk_buff *skb,
...
{
...
rcu_read_lock();
indev = __in_dev_get_rcu(skb->dev);
if (indev != NULL) {
ifa = indev->ifa_list;
newdst = ifa->ifa_local; <---
}
rcu_read_unlock();
...
}
Before the commit, 'ifa' had been always checked before access. After the
commit, however, it could be accessed even if it's NULL. Interestingly,
this was once fixed in 2003.
http://marc.info/?l=netfilter-devel&m=106668497403047&w=2
In addition to the original one, we have seen the crash when packets that
need to be redirected somehow arrive on an interface which hasn't been
yet fully configured.
This change just reverts the logic to the old behavior to avoid the crash.
Fixes: 8b13eddfdf04 ("netfilter: refactor NAT redirect IPv4 to use it from nf_tables")
Signed-off-by: Munehisa Kamata <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[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: static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
if (!scsi_block_when_processing_errors(sdev))
return -ENODEV;
if (sdev->host->hostt->compat_ioctl) {
int ret;
ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg);
return ret;
}
/*
* Let the static ioctl translation table take care of it.
*/
return -ENOIOCTLCMD;
}
Commit Message: block: fail SCSI passthrough ioctls on partition devices
Linux allows executing the SG_IO ioctl on a partition or LVM volume, and
will pass the command to the underlying block device. This is
well-known, but it is also a large security problem when (via Unix
permissions, ACLs, SELinux or a combination thereof) a program or user
needs to be granted access only to part of the disk.
This patch lets partitions forward a small set of harmless ioctls;
others are logged with printk so that we can see which ioctls are
actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred.
Of course it was being sent to a (partition on a) hard disk, so it would
have failed with ENOTTY and the patch isn't changing anything in
practice. Still, I'm treating it specially to avoid spamming the logs.
In principle, this restriction should include programs running with
CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and
/dev/sdb, it still should not be able to read/write outside the
boundaries of /dev/sda2 independent of the capabilities. However, for
now programs with CAP_SYS_RAWIO will still be allowed to send the
ioctls. Their actions will still be logged.
This patch does not affect the non-libata IDE driver. That driver
however already tests for bd != bd->bd_contains before issuing some
ioctl; it could be restricted further to forbid these ioctls even for
programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO.
Cc: [email protected]
Cc: Jens Axboe <[email protected]>
Cc: James Bottomley <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
[ Make it also print the command name when warning - Linus ]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int decode(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq)
{
rc->code -= cumFreq * rc->range;
rc->range *= freq;
while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) {
unsigned byte = bytestream2_get_byte(gb);
rc->code = (rc->code << 8) | byte;
rc->range <<= 8;
}
return 0;
}
Commit Message: avcodec/scpr: Check y in first line loop in decompress_i()
Fixes: out of array access
Fixes: 1478/clusterfuzz-testcase-minimized-5285486908145664
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-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: xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData,
name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
ctxt->instate = XML_PARSER_EOF;
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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 NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
{
int status = 0;
return status;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderViewHostImpl::OnUpdateTitle(
int32 page_id,
const string16& title,
WebKit::WebTextDirection title_direction) {
if (title.length() > kMaxTitleChars) {
NOTREACHED() << "Renderer sent too many characters in title.";
return;
}
delegate_->UpdateTitle(this, page_id, title,
WebTextDirectionToChromeTextDirection(
title_direction));
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
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 GLSurfaceEGLSurfaceControl::ScheduleOverlayPlane(
int z_order,
gfx::OverlayTransform transform,
GLImage* image,
const gfx::Rect& bounds_rect,
const gfx::RectF& crop_rect,
bool enable_blend,
std::unique_ptr<gfx::GpuFence> gpu_fence) {
if (!pending_transaction_)
pending_transaction_.emplace();
bool uninitialized = false;
if (pending_surfaces_count_ == surface_list_.size()) {
uninitialized = true;
surface_list_.emplace_back(*root_surface_);
}
pending_surfaces_count_++;
auto& surface_state = surface_list_.at(pending_surfaces_count_ - 1);
if (uninitialized || surface_state.z_order != z_order) {
surface_state.z_order = z_order;
pending_transaction_->SetZOrder(*surface_state.surface, z_order);
}
AHardwareBuffer* hardware_buffer = nullptr;
base::ScopedFD fence_fd;
auto scoped_hardware_buffer = image->GetAHardwareBuffer();
if (scoped_hardware_buffer) {
hardware_buffer = scoped_hardware_buffer->buffer();
fence_fd = scoped_hardware_buffer->TakeFence();
auto* a_surface = surface_state.surface->surface();
DCHECK_EQ(pending_frame_resources_.count(a_surface), 0u);
auto& resource_ref = pending_frame_resources_[a_surface];
resource_ref.surface = surface_state.surface;
resource_ref.scoped_buffer = std::move(scoped_hardware_buffer);
}
if (uninitialized || surface_state.hardware_buffer != hardware_buffer) {
surface_state.hardware_buffer = hardware_buffer;
if (!fence_fd.is_valid() && gpu_fence && surface_state.hardware_buffer) {
auto fence_handle =
gfx::CloneHandleForIPC(gpu_fence->GetGpuFenceHandle());
DCHECK(!fence_handle.is_null());
fence_fd = base::ScopedFD(fence_handle.native_fd.fd);
}
pending_transaction_->SetBuffer(*surface_state.surface,
surface_state.hardware_buffer,
std::move(fence_fd));
}
if (hardware_buffer) {
gfx::Rect dst = bounds_rect;
gfx::Size buffer_size = GetBufferSize(hardware_buffer);
gfx::RectF scaled_rect =
gfx::RectF(crop_rect.x() * buffer_size.width(),
crop_rect.y() * buffer_size.height(),
crop_rect.width() * buffer_size.width(),
crop_rect.height() * buffer_size.height());
gfx::Rect src = gfx::ToEnclosedRect(scaled_rect);
if (uninitialized || surface_state.src != src || surface_state.dst != dst ||
surface_state.transform != transform) {
surface_state.src = src;
surface_state.dst = dst;
surface_state.transform = transform;
pending_transaction_->SetGeometry(*surface_state.surface, src, dst,
transform);
}
}
bool opaque = !enable_blend;
if (uninitialized || surface_state.opaque != opaque) {
surface_state.opaque = opaque;
pending_transaction_->SetOpaque(*surface_state.surface, opaque);
}
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:
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: cib_remote_listen(gpointer data)
{
int lpc = 0;
int csock = 0;
unsigned laddr;
time_t now = 0;
time_t start = time(NULL);
struct sockaddr_in addr;
int ssock = *(int *)data;
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_session *session = NULL;
#endif
cib_client_t *new_client = NULL;
xmlNode *login = NULL;
const char *user = NULL;
const char *pass = NULL;
const char *tmp = NULL;
#ifdef HAVE_DECL_NANOSLEEP
const struct timespec sleepfast = { 0, 10000000 }; /* 10 millisec */
#endif
static struct mainloop_fd_callbacks remote_client_fd_callbacks =
{
.dispatch = cib_remote_msg,
.destroy = cib_remote_connection_destroy,
};
/* accept the connection */
laddr = sizeof(addr);
csock = accept(ssock, (struct sockaddr *)&addr, &laddr);
crm_debug("New %s connection from %s",
ssock == remote_tls_fd ? "secure" : "clear-text", inet_ntoa(addr.sin_addr));
if (csock == -1) {
crm_err("accept socket failed");
return TRUE;
}
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
/* create gnutls session for the server socket */
session = create_tls_session(csock, GNUTLS_SERVER);
if (session == NULL) {
crm_err("TLS session creation failed");
close(csock);
return TRUE;
}
#endif
}
do {
crm_trace("Iter: %d", lpc++);
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
login = crm_recv_remote_msg(session, TRUE);
#endif
} else {
login = crm_recv_remote_msg(GINT_TO_POINTER(csock), FALSE);
}
if (login != NULL) {
break;
}
#ifdef HAVE_DECL_NANOSLEEP
nanosleep(&sleepfast, NULL);
#else
sleep(1);
#endif
now = time(NULL);
/* Peers have 3s to connect */
} while (login == NULL && (start - now) < 4);
crm_log_xml_info(login, "Login: ");
if (login == NULL) {
goto bail;
}
tmp = crm_element_name(login);
if (safe_str_neq(tmp, "cib_command")) {
crm_err("Wrong tag: %s", tmp);
goto bail;
}
tmp = crm_element_value(login, "op");
if (safe_str_neq(tmp, "authenticate")) {
crm_err("Wrong operation: %s", tmp);
goto bail;
}
user = crm_element_value(login, "user");
pass = crm_element_value(login, "password");
/* Non-root daemons can only validate the password of the
* user they're running as
*/
if (check_group_membership(user, CRM_DAEMON_GROUP) == FALSE) {
crm_err("User is not a member of the required group");
goto bail;
} else if (authenticate_user(user, pass) == FALSE) {
crm_err("PAM auth failed");
goto bail;
}
/* send ACK */
num_clients++;
new_client = calloc(1, sizeof(cib_client_t));
new_client->name = crm_element_value_copy(login, "name");
CRM_CHECK(new_client->id == NULL, free(new_client->id));
new_client->id = crm_generate_uuid();
#if ENABLE_ACL
new_client->user = strdup(user);
#endif
new_client->callback_id = NULL;
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
new_client->encrypted = TRUE;
new_client->session = session;
#endif
} else {
new_client->session = GINT_TO_POINTER(csock);
}
free_xml(login);
login = create_xml_node(NULL, "cib_result");
crm_xml_add(login, F_CIB_OPERATION, CRM_OP_REGISTER);
crm_xml_add(login, F_CIB_CLIENTID, new_client->id);
crm_send_remote_msg(new_client->session, login, new_client->encrypted);
free_xml(login);
new_client->remote = mainloop_add_fd(
"cib-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &remote_client_fd_callbacks);
g_hash_table_insert(client_list, new_client->id, new_client);
return TRUE;
bail:
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_bye(*session, GNUTLS_SHUT_RDWR);
gnutls_deinit(*session);
gnutls_free(session);
#endif
}
close(csock);
free_xml(login);
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: CIFSSMBFlush(const int xid, struct cifs_tcon *tcon, int smb_file_id)
{
int rc = 0;
FLUSH_REQ *pSMB = NULL;
cFYI(1, "In CIFSSMBFlush");
rc = small_smb_init(SMB_COM_FLUSH, 1, tcon, (void **) &pSMB);
if (rc)
return rc;
pSMB->FileID = (__u16) smb_file_id;
pSMB->ByteCount = 0;
rc = SendReceiveNoRsp(xid, tcon->ses, (struct smb_hdr *) pSMB, 0);
cifs_stats_inc(&tcon->num_flushes);
if (rc)
cERROR(1, "Send error in Flush = %d", rc);
return rc;
}
Commit Message: cifs: fix possible memory corruption in CIFSFindNext
The name_len variable in CIFSFindNext is a signed int that gets set to
the resume_name_len in the cifs_search_info. The resume_name_len however
is unsigned and for some infolevels is populated directly from a 32 bit
value sent by the server.
If the server sends a very large value for this, then that value could
look negative when converted to a signed int. That would make that
value pass the PATH_MAX check later in CIFSFindNext. The name_len would
then be used as a length value for a memcpy. It would then be treated
as unsigned again, and the memcpy scribbles over a ton of memory.
Fix this by making the name_len an unsigned value in CIFSFindNext.
Cc: <[email protected]>
Reported-by: Darren Lavender <[email protected]>
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[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: iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
struct sc_context *ctx = card->ctx;
struct sc_iin *iin = &card->serialnr.iin;
struct sc_apdu apdu;
unsigned char rbuf[0xC0];
size_t ii, offs;
int rv;
LOG_FUNC_CALLED(ctx);
if (card->serialnr.len)
goto end;
memset(&card->serialnr, 0, sizeof(card->serialnr));
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0);
apdu.le = sizeof(rbuf);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed");
if (rbuf[0] != ISO7812_PAN_SN_TAG)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error");
iin->mii = (rbuf[2] >> 4) & 0x0F;
iin->country = 0;
for (ii=5; ii<8; ii++) {
iin->country *= 10;
iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F;
}
iin->issuer_id = 0;
for (ii=8; ii<10; ii++) {
iin->issuer_id *= 10;
iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F;
}
offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0;
if (card->type == SC_CARD_TYPE_IASECC_SAGEM) {
/* 5A 0A 92 50 00 20 10 10 25 00 01 3F */
/* 00 02 01 01 02 50 00 13 */
for (ii=0; ii < rbuf[1] - offs; ii++)
*(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4)
+ ((rbuf[ii + offs + 2] & 0xF0) >> 4) ;
card->serialnr.len = ii;
}
else {
for (ii=0; ii < rbuf[1] - offs; ii++)
*(card->serialnr.value + ii) = rbuf[ii + offs + 2];
card->serialnr.len = ii;
}
do {
char txt[0x200];
for (ii=0;ii<card->serialnr.len;ii++)
sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii));
sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id);
} while(0);
end:
if (serial)
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
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: | 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: cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-13052/CFM: refine decoding of the Sender ID TLV
In cfm_network_addr_print() add a length argument and use it to validate
the input buffer.
In cfm_print() add a length check for MAC address chassis ID. Supply
cfm_network_addr_print() with the length of its buffer and a correct
pointer to the buffer (it was off-by-one before). Change some error
handling blocks to skip to the next TLV in the current PDU rather than to
stop decoding the PDU. Print the management domain and address contents,
although in hex only so far.
Add some comments to clarify the code flow and to tell exact sections in
IEEE standard documents. Add new error messages and make some existing
messages more specific.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: xdr_krb5_enctype(XDR *xdrs, krb5_enctype *objp)
{
/*
* This used to be xdr_krb5_keytype, but keytypes and enctypes have
* been merged into only enctypes. However, randkey_principal
* already ensures that only a key of ENCTYPE_DES_CBC_CRC will be
* returned to v1 clients, and ENCTYPE_DES_CBC_CRC has the same
* value as KEYTYPE_DES used too, which is what all v1 clients
* expect. Therefore, IMHO, just encoding whatever enctype we get
* is safe.
*/
if (!xdr_int32(xdrs, (int32_t *) objp))
return (FALSE);
return (TRUE);
}
Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421]
[MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free
partial deserialization results upon failure to deserialize. This
responsibility belongs to the callers, svctcp_getargs() and
svcudp_getargs(); doing it in the unwrap function results in freeing
the results twice.
In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers
we are freeing, as other XDR functions such as xdr_bytes() and
xdr_string().
ticket: 8056 (new)
target_version: 1.13.1
tags: pullup
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 inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
err = xt_check_entry_offsets(e, e->target_offset, e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[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 bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19
Target: 1
Example 2:
Code: static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
{
struct audio_device *adev = (struct audio_device *)dev;
int err = 0;
pthread_mutex_lock(&adev->lock);
adev->mic_mute = state;
if (adev->mode == AUDIO_MODE_IN_CALL) {
/* TODO */
}
pthread_mutex_unlock(&adev->lock);
return err;
}
Commit Message: Fix audio record pre-processing
proc_buf_out consistently initialized.
intermediate scratch buffers consistently initialized.
prevent read failure from overwriting memory.
Test: POC, CTS, camera record
Bug: 62873231
Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686
(cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb)
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: LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
{
if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
return containingBlockLogicalWidthForPositioned(containingBlock, false);
if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
const RenderView* view = toRenderView(containingBlock);
if (FrameView* frameView = view->frameView()) {
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
}
}
if (containingBlock->isBox()) {
const RenderBlock* cb = containingBlock->isRenderBlock() ?
toRenderBlock(containingBlock) : containingBlock->containingBlock();
return cb->clientLogicalHeight();
}
ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
const RenderInline* flow = toRenderInline(containingBlock);
InlineFlowBox* first = flow->firstLineBox();
InlineFlowBox* last = flow->lastLineBox();
if (!first || !last)
return 0;
LayoutUnit heightResult;
LayoutRect boundingBox = flow->linesBoundingBox();
if (containingBlock->isHorizontalWritingMode())
heightResult = boundingBox.height();
else
heightResult = boundingBox.width();
heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
return heightResult;
}
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
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: _WM_ParseNewHmp(uint8_t *hmp_data, uint32_t hmp_size) {
uint8_t is_hmp2 = 0;
uint32_t zero_cnt = 0;
uint32_t i = 0;
uint32_t hmp_file_length = 0;
uint32_t hmp_chunks = 0;
uint32_t hmp_divisions = 0;
uint32_t hmp_unknown = 0;
uint32_t hmp_bpm = 0;
uint32_t hmp_song_time = 0;
struct _mdi *hmp_mdi;
uint8_t **hmp_chunk;
uint32_t *chunk_length;
uint32_t *chunk_ofs;
uint32_t *chunk_delta;
uint8_t *chunk_end;
uint32_t chunk_num = 0;
uint32_t hmp_track = 0;
uint32_t smallest_delta = 0;
uint32_t subtract_delta = 0;
uint32_t end_of_chunks = 0;
uint32_t var_len_shift = 0;
float tempo_f = 500000.0;
float samples_per_delta_f = 0.0;
uint32_t sample_count = 0;
float sample_count_f = 0;
float sample_remainder = 0;
if (memcmp(hmp_data, "HMIMIDIP", 8)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
hmp_data += 8;
hmp_size -= 8;
if (!memcmp(hmp_data, "013195", 6)) {
hmp_data += 6;
hmp_size -= 6;
is_hmp2 = 1;
}
if (is_hmp2) {
zero_cnt = 18;
} else {
zero_cnt = 24;
}
for (i = 0; i < zero_cnt; i++) {
if (hmp_data[i] != 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
}
hmp_data += zero_cnt;
hmp_size -= zero_cnt;
hmp_file_length = *hmp_data++;
hmp_file_length += (*hmp_data++ << 8);
hmp_file_length += (*hmp_data++ << 16);
hmp_file_length += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_file_length);
hmp_data += 12;
hmp_size -= 12;
hmp_chunks = *hmp_data++;
hmp_chunks += (*hmp_data++ << 8);
hmp_chunks += (*hmp_data++ << 16);
hmp_chunks += (*hmp_data++ << 24);
hmp_size -= 4;
hmp_unknown = *hmp_data++;
hmp_unknown += (*hmp_data++ << 8);
hmp_unknown += (*hmp_data++ << 16);
hmp_unknown += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_unknown);
hmp_divisions = 60;
hmp_bpm = *hmp_data++;
hmp_bpm += (*hmp_data++ << 8);
hmp_bpm += (*hmp_data++ << 16);
hmp_bpm += (*hmp_data++ << 24);
hmp_size -= 4;
/* Slow but needed for accuracy */
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / hmp_bpm) + 0.5f;
} else {
tempo_f = (float) (60000000 / hmp_bpm);
}
samples_per_delta_f = _WM_GetSamplesPerTick(hmp_divisions, tempo_f);
hmp_song_time = *hmp_data++;
hmp_song_time += (*hmp_data++ << 8);
hmp_song_time += (*hmp_data++ << 16);
hmp_song_time += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_song_time);
if (is_hmp2) {
hmp_data += 840;
hmp_size -= 840;
} else {
hmp_data += 712;
hmp_size -= 712;
}
hmp_mdi = _WM_initMDI();
_WM_midi_setup_divisions(hmp_mdi, hmp_divisions);
_WM_midi_setup_tempo(hmp_mdi, (uint32_t)tempo_f);
hmp_chunk = malloc(sizeof(uint8_t *) * hmp_chunks);
chunk_length = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_delta = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_ofs = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_end = malloc(sizeof(uint8_t) * hmp_chunks);
smallest_delta = 0xffffffff;
for (i = 0; i < hmp_chunks; i++) {
hmp_chunk[i] = hmp_data;
chunk_ofs[i] = 0;
chunk_num = *hmp_data++;
chunk_num += (*hmp_data++ << 8);
chunk_num += (*hmp_data++ << 16);
chunk_num += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(chunk_num);
chunk_length[i] = *hmp_data++;
chunk_length[i] += (*hmp_data++ << 8);
chunk_length[i] += (*hmp_data++ << 16);
chunk_length[i] += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
if (chunk_length[i] > hmp_size) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0);
goto _hmp_end;
}
hmp_size -= chunk_length[i];
hmp_track = *hmp_data++;
hmp_track += (*hmp_data++ << 8);
hmp_track += (*hmp_data++ << 16);
hmp_track += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(hmp_track);
chunk_delta[i] = 0;
var_len_shift = 0;
if (*hmp_data < 0x80) {
do {
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
var_len_shift += 7;
chunk_ofs[i]++;
} while (*hmp_data < 0x80);
}
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
chunk_ofs[i]++;
if (chunk_delta[i] < smallest_delta) {
smallest_delta = chunk_delta[i];
}
hmp_data = hmp_chunk[i] + chunk_length[i];
hmp_chunk[i] += chunk_ofs[i]++;
chunk_end[i] = 0;
}
subtract_delta = smallest_delta;
sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
while (end_of_chunks < hmp_chunks) {
smallest_delta = 0;
for (i = 0; i < hmp_chunks; i++) {
if (chunk_end[i])
continue;
if (chunk_delta[i]) {
chunk_delta[i] -= subtract_delta;
if (chunk_delta[i]) {
if ((!smallest_delta)
|| (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
continue;
}
}
do {
if (((hmp_chunk[i][0] & 0xf0) == 0xb0 ) && ((hmp_chunk[i][1] == 110) || (hmp_chunk[i][1] == 111)) && (hmp_chunk[i][2] > 0x7f)) {
hmp_chunk[i] += 3;
} else {
uint32_t setup_ret = 0;
if ((setup_ret = _WM_SetupMidiEvent(hmp_mdi, hmp_chunk[i], 0)) == 0) {
goto _hmp_end;
}
if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x2f) && (hmp_chunk[i][2] == 0x00)) {
/* End of Chunk */
end_of_chunks++;
chunk_end[i] = 1;
hmp_chunk[i] += 3;
goto NEXT_CHUNK;
} else if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x51) && (hmp_chunk[i][2] == 0x03)) {
/* Tempo */
tempo_f = (float)((hmp_chunk[i][3] << 16) + (hmp_chunk[i][4] << 8)+ hmp_chunk[i][5]);
if (tempo_f == 0.0)
tempo_f = 500000.0;
fprintf(stderr,"DEBUG: Tempo change %f\r\n", tempo_f);
}
hmp_chunk[i] += setup_ret;
}
var_len_shift = 0;
chunk_delta[i] = 0;
if (*hmp_chunk[i] < 0x80) {
do {
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
var_len_shift += 7;
hmp_chunk[i]++;
} while (*hmp_chunk[i] < 0x80);
}
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
hmp_chunk[i]++;
} while (!chunk_delta[i]);
if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
NEXT_CHUNK: continue;
}
subtract_delta = smallest_delta;
sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
}
if ((hmp_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _hmp_end;
}
hmp_mdi->extra_info.current_sample = 0;
hmp_mdi->current_event = &hmp_mdi->events[0];
hmp_mdi->samples_to_mix = 0;
hmp_mdi->note = NULL;
_WM_ResetToStart(hmp_mdi);
_hmp_end:
free(hmp_chunk);
free(chunk_length);
free(chunk_delta);
free(chunk_ofs);
free(chunk_end);
if (hmp_mdi->reverb) return (hmp_mdi);
_WM_freeMDI(hmp_mdi);
return NULL;
}
Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows
where to stop reading, and adjust its users properly. Fixes bug #175
(CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.)
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void r_bin_object_delete_items(RBinObject *o) {
ut32 i = 0;
if (!o) {
return;
}
r_list_free (o->entries);
r_list_free (o->fields);
r_list_free (o->imports);
r_list_free (o->libs);
r_list_free (o->relocs);
r_list_free (o->sections);
r_list_free (o->strings);
r_list_free (o->symbols);
r_list_free (o->classes);
r_list_free (o->lines);
sdb_free (o->kv);
if (o->mem) {
o->mem->free = mem_free;
}
r_list_free (o->mem);
o->mem = NULL;
o->entries = NULL;
o->fields = NULL;
o->imports = NULL;
o->libs = NULL;
o->relocs = NULL;
o->sections = NULL;
o->strings = NULL;
o->symbols = NULL;
o->classes = NULL;
o->lines = NULL;
o->info = NULL;
o->kv = NULL;
for (i = 0; i < R_BIN_SYM_LAST; i++) {
free (o->binsym[i]);
o->binsym[i] = NULL;
}
}
Commit Message: Fix #8748 - Fix oobread on string search
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void become_daemon(const char *pidfile)
{
#ifndef _WIN32
pid_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
if (pidfile) {
if (!ga_open_pidfile(pidfile)) {
g_critical("failed to create pidfile");
exit(EXIT_FAILURE);
}
}
umask(0);
sid = setsid();
if (sid < 0) {
goto fail;
}
if ((chdir("/")) < 0) {
goto fail;
}
reopen_fd_to_null(STDIN_FILENO);
reopen_fd_to_null(STDOUT_FILENO);
reopen_fd_to_null(STDERR_FILENO);
return;
fail:
if (pidfile) {
unlink(pidfile);
}
g_critical("failed to daemonize");
exit(EXIT_FAILURE);
#endif
}
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: static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb,
int len)
{
struct igmphdr *ih = igmp_hdr(skb);
struct igmpv3_query *ih3 = igmpv3_query_hdr(skb);
struct ip_mc_list *im;
__be32 group = ih->group;
int max_delay;
int mark = 0;
if (len == 8) {
if (ih->code == 0) {
/* Alas, old v1 router presents here. */
max_delay = IGMP_Query_Response_Interval;
in_dev->mr_v1_seen = jiffies +
IGMP_V1_Router_Present_Timeout;
group = 0;
} else {
/* v2 router present */
max_delay = ih->code*(HZ/IGMP_TIMER_SCALE);
in_dev->mr_v2_seen = jiffies +
IGMP_V2_Router_Present_Timeout;
}
/* cancel the interface change timer */
in_dev->mr_ifc_count = 0;
if (del_timer(&in_dev->mr_ifc_timer))
__in_dev_put(in_dev);
/* clear deleted report items */
igmpv3_clear_delrec(in_dev);
} else if (len < 12) {
return; /* ignore bogus packet; freed by caller */
} else if (IGMP_V1_SEEN(in_dev)) {
/* This is a v3 query with v1 queriers present */
max_delay = IGMP_Query_Response_Interval;
group = 0;
} else if (IGMP_V2_SEEN(in_dev)) {
/* this is a v3 query with v2 queriers present;
* Interpretation of the max_delay code is problematic here.
* A real v2 host would use ih_code directly, while v3 has a
* different encoding. We use the v3 encoding as more likely
* to be intended in a v3 query.
*/
max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);
} else { /* v3 */
if (!pskb_may_pull(skb, sizeof(struct igmpv3_query)))
return;
ih3 = igmpv3_query_hdr(skb);
if (ih3->nsrcs) {
if (!pskb_may_pull(skb, sizeof(struct igmpv3_query)
+ ntohs(ih3->nsrcs)*sizeof(__be32)))
return;
ih3 = igmpv3_query_hdr(skb);
}
max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);
if (!max_delay)
max_delay = 1; /* can't mod w/ 0 */
in_dev->mr_maxdelay = max_delay;
if (ih3->qrv)
in_dev->mr_qrv = ih3->qrv;
if (!group) { /* general query */
if (ih3->nsrcs)
return; /* no sources allowed */
igmp_gq_start_timer(in_dev);
return;
}
/* mark sources to include, if group & source-specific */
mark = ih3->nsrcs != 0;
}
/*
* - Start the timers in all of our membership records
* that the query applies to for the interface on
* which the query arrived excl. those that belong
* to a "local" group (224.0.0.X)
* - For timers already running check if they need to
* be reset.
* - Use the igmp->igmp_code field as the maximum
* delay possible
*/
rcu_read_lock();
for_each_pmc_rcu(in_dev, im) {
int changed;
if (group && group != im->multiaddr)
continue;
if (im->multiaddr == IGMP_ALL_HOSTS)
continue;
spin_lock_bh(&im->lock);
if (im->tm_running)
im->gsquery = im->gsquery && mark;
else
im->gsquery = mark;
changed = !im->gsquery ||
igmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs);
spin_unlock_bh(&im->lock);
if (changed)
igmp_mod_timer(im, max_delay);
}
rcu_read_unlock();
}
Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries
Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP
behavior on v3 query during v2-compatibility mode') added yet another
case for query parsing, which can result in max_delay = 0. Substitute
a value of 1, as in the usual v3 case.
Reported-by: Simon McVittie <[email protected]>
References: http://bugs.debian.org/654876
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int check_newline(const char *progname, const char *name)
{
const char *s;
for (s = "\n"; *s; s++) {
if (strchr(name, *s)) {
fprintf(stderr,
"%s: illegal character 0x%02x in mount entry\n",
progname, *s);
return EX_USAGE;
}
}
return 0;
}
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: bool OmniboxViewViews::ShouldShowPlaceholderText() const {
return Textfield::ShouldShowPlaceholderText() &&
!model()->is_caret_visible() && !model()->is_keyword_selected();
}
Commit Message: omnibox: experiment with restoring placeholder when caret shows
Shows the "Search Google or type a URL" omnibox placeholder even when
the caret (text edit cursor) is showing / when focused. views::Textfield
works this way, as does <input placeholder="">. Omnibox and the NTP's
"fakebox" are exceptions in this regard and this experiment makes this
more consistent.
[email protected]
BUG=955585
Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315
Commit-Queue: Dan Beam <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654279}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
PixelPacket *q;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(depth,BImgBuff,i,image);
}
(void) SyncImage(image);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
if(GetCutColors(image)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(q) == ScaleCharToQuantum(1))
{
SetPixelRed(q,QuantumRange);
SetPixelGreen(q,QuantumRange);
SetPixelBlue(q,QuantumRange);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1599
CWE ID: CWE-20
Target: 1
Example 2:
Code: void DisplaySourceCustomBindings::DispatchSessionTerminated(int sink_id) const {
v8::Isolate* isolate = context()->isolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context()->v8_context());
v8::Local<v8::Array> event_args = v8::Array::New(isolate, 1);
event_args->Set(0, v8::Integer::New(isolate, sink_id));
context()->DispatchEvent("displaySource.onSessionTerminated", event_args);
}
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
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 NavigationControllerImpl::RendererDidNavigateToExistingPage(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
bool is_same_document,
bool was_restored,
NavigationHandleImpl* handle) {
DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
<< "that a last committed entry exists.";
DCHECK(!rfh->GetParent());
NavigationEntryImpl* entry;
if (params.intended_as_new_entry) {
entry = GetLastCommittedEntry();
if (!is_same_document)
entry->GetSSL() = SSLStatus(handle->GetSSLInfo());
if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
handle->GetNetErrorCode() == net::OK) {
bool has_cert = !!entry->GetSSL().certificate;
if (is_same_document) {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageSameDocumentIntendedAsNew",
has_cert);
} else {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageDifferentDocumentIntendedAsNew",
has_cert);
}
}
} else if (params.nav_entry_id) {
entry = GetEntryWithUniqueID(params.nav_entry_id);
if (is_same_document) {
NavigationEntryImpl* last_entry = GetLastCommittedEntry();
if (entry->GetURL().GetOrigin() == last_entry->GetURL().GetOrigin() &&
last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
was_restored) {
entry->GetSSL() = last_entry->GetSSL();
}
} else {
if (handle->GetSSLInfo().is_valid()) {
entry->GetSSL() = SSLStatus(handle->GetSSLInfo());
} else if (entry->GetURL().GetOrigin() != handle->GetURL().GetOrigin()) {
entry->GetSSL() = SSLStatus();
}
}
if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
handle->GetNetErrorCode() == net::OK) {
bool has_cert = !!entry->GetSSL().certificate;
if (is_same_document && was_restored) {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageSameDocumentRestoredBrowserInitiated",
has_cert);
} else if (is_same_document && !was_restored) {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageSameDocumentBrowserInitiated",
has_cert);
} else if (!is_same_document && was_restored) {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageRestoredBrowserInitiated",
has_cert);
} else {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus.ExistingPageBrowserInitiated",
has_cert);
}
}
} else {
entry = GetLastCommittedEntry();
CopyReplacedNavigationEntryDataIfPreviouslyEmpty(*entry, entry);
if (!is_same_document)
entry->GetSSL() = SSLStatus(handle->GetSSLInfo());
if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
handle->GetNetErrorCode() == net::OK) {
bool has_cert = !!entry->GetSSL().certificate;
if (is_same_document) {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageSameDocumentRendererInitiated",
has_cert);
} else {
UMA_HISTOGRAM_BOOLEAN(
"Navigation.SecureSchemeHasSSLStatus."
"ExistingPageDifferentDocumentRendererInitiated",
has_cert);
}
}
}
DCHECK(entry);
entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
: PAGE_TYPE_NORMAL);
entry->SetURL(params.url);
entry->SetReferrer(params.referrer);
if (entry->update_virtual_url_with_url())
UpdateVirtualURLToURL(entry, params.url);
DCHECK(entry->site_instance() == nullptr ||
!entry->GetRedirectChain().empty() ||
entry->site_instance() == rfh->GetSiteInstance());
entry->AddOrUpdateFrameEntry(
rfh->frame_tree_node(), params.item_sequence_number,
params.document_sequence_number, rfh->GetSiteInstance(), nullptr,
params.url, params.referrer, params.redirects, params.page_state,
params.method, params.post_id, nullptr /* blob_url_loader_factory */);
if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
entry->GetFavicon() = FaviconStatus();
DiscardNonCommittedEntriesInternal();
last_committed_entry_index_ = GetIndexOfEntry(entry);
}
Commit Message: Preserve renderer-initiated bit when reloading in a new process.
BUG=847718
TEST=See bug for repro steps.
Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227
Reviewed-on: https://chromium-review.googlesource.com/1080235
Commit-Queue: Charlie Reis <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563312}
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: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: struct key *key_lookup(key_serial_t id)
{
struct rb_node *n;
struct key *key;
spin_lock(&key_serial_lock);
/* search the tree for the specified key */
n = key_serial_tree.rb_node;
while (n) {
key = rb_entry(n, struct key, serial_node);
if (id < key->serial)
n = n->rb_left;
else if (id > key->serial)
n = n->rb_right;
else
goto found;
}
not_found:
key = ERR_PTR(-ENOKEY);
goto error;
found:
/* A key is allowed to be looked up only if someone still owns a
* reference to it - otherwise it's awaiting the gc.
*/
if (!refcount_inc_not_zero(&key->usage))
goto not_found;
error:
spin_unlock(&key_serial_lock);
return key;
}
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: 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 const char *getname(RBin *bin, int type, int idx) {
RBinFile *a = r_bin_cur (bin);
RBinPlugin *plugin = r_bin_file_cur_plugin (a);
if (plugin && plugin->get_name) {
return plugin->get_name (a, type, idx);
}
return NULL;
}
Commit Message: Fix #8748 - Fix oobread on string search
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 int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
op->size = 1;
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (data[1] <= 127)
op->jump = addr + data[1] + op->size;
else op->jump = addr - (256 - data[1]) + op->size;
op->fail = addr + op->size;
_6502_anal_esil_ccall (op, data[0]);
break;
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
}
Commit Message: Fix #10294 - crash in r2_hoobr__6502_op
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void limitedWithInvalidAndMissingDefaultAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObject* imp = V8TestObject::toNative(info.Holder());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
imp->setAttribute(HTMLNames::limitedwithinvalidandmissingdefaultattributeAttr, cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::string PrintPreviewUI::GetPrintPreviewUIAddress() const {
char preview_ui_addr[2 + (2 * sizeof(this)) + 1];
base::snprintf(preview_ui_addr, sizeof(preview_ui_addr), "%p", this);
return preview_ui_addr;
}
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
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: image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: FindBarController::~FindBarController() {
DCHECK(!tab_contents_);
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 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: base::SharedMemoryHandle CreateMSKPInSharedMemory() {
SkDynamicMemoryWStream stream;
sk_sp<SkDocument> doc = SkMakeMultiPictureDocument(&stream);
cc::SkiaPaintCanvas canvas(doc->beginPage(800, 600));
SkRect rect = SkRect::MakeXYWH(10, 10, 250, 250);
cc::PaintFlags flags;
flags.setAntiAlias(false);
flags.setColor(SK_ColorRED);
flags.setStyle(cc::PaintFlags::kFill_Style);
canvas.drawRect(rect, flags);
doc->endPage();
doc->close();
size_t len = stream.bytesWritten();
base::SharedMemoryCreateOptions options;
options.size = len;
options.share_read_only = true;
base::SharedMemory shared_memory;
if (shared_memory.Create(options) && shared_memory.Map(len)) {
stream.copyTo(shared_memory.memory());
return base::SharedMemory::DuplicateHandle(shared_memory.handle());
}
return base::SharedMemoryHandle();
}
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
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 parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)
{
/* OpenSc Operation values for each command operation-type */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
u8 bValue;
int i;
int iKeyRef = 0;
int iMethod;
int iPinCount;
int iOffset = 0;
int iOperation;
const int* p_idx;
/* Check all sub-AC definitions within the total AC */
while (len > 1) { /* minimum length = 2 */
int iACLen = buf[iOffset] & 0x0F;
iPinCount = -1; /* default no pin required */
iMethod = SC_AC_NONE; /* default no authentication required */
if (buf[iOffset] & 0X80) { /* AC in adaptive coding */
/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */
int iParmLen = 1; /* command-byte is always present */
int iKeyLen = 0; /* Encryption key is optional */
if (buf[iOffset] & 0x20) iKeyLen++;
if (buf[iOffset+1] & 0x40) iParmLen++;
if (buf[iOffset+1] & 0x20) iParmLen++;
if (buf[iOffset+1] & 0x10) iParmLen++;
if (buf[iOffset+1] & 0x08) iParmLen++;
/* Get KeyNumber if available */
if(iKeyLen) {
int iSC = buf[iOffset+iACLen];
switch( (iSC>>5) & 0x03 ){
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
}
/* Get PinNumber if available */
if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */
iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */
iMethod = SC_AC_CHV;
}
/* Convert SETCOS command to OpenSC command group */
switch(buf[iOffset+2]){
case 0x2A: /* crypto operation */
iOperation = SC_AC_OP_CRYPTO;
break;
case 0x46: /* key-generation operation */
iOperation = SC_AC_OP_UPDATE;
break;
default:
iOperation = SC_AC_OP_SELECT;
break;
}
sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);
}
else { /* AC in simple coding */
/* Initial AC is treated as an operational AC */
/* Get specific Cmd groups for specified file-type */
switch (file->type) {
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* EF */
p_idx = ef_idx;
break;
}
/* Encryption key present ? */
iPinCount = iACLen - 1;
if (buf[iOffset] & 0x20) {
int iSC = buf[iOffset + iACLen];
switch( (iSC>>5) & 0x03 ) {
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
iPinCount--; /* one byte used for keyReference */
}
/* Pin present ? */
if ( iPinCount > 0 ) {
iKeyRef = buf[iOffset + 2]; /* pin ref */
iMethod = SC_AC_CHV;
}
/* Add AC for each command-operationType into OpenSc structure */
bValue = buf[iOffset + 1];
for (i = 0; i < 8; i++) {
if((bValue & 1) && (p_idx[i] >= 0))
sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);
bValue >>= 1;
}
}
/* Current field treated, get next AC sub-field */
iOffset += iACLen +1; /* AC + PTL-byte */
len -= iACLen +1;
}
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: AutomationProvider::AutomationProvider(Profile* profile)
: profile_(profile),
reply_message_(NULL),
is_connected_(false),
initial_loads_complete_(false) {
TRACE_EVENT_BEGIN("AutomationProvider::AutomationProvider", 0, "");
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
browser_tracker_.reset(new AutomationBrowserTracker(this));
extension_tracker_.reset(new AutomationExtensionTracker(this));
tab_tracker_.reset(new AutomationTabTracker(this));
window_tracker_.reset(new AutomationWindowTracker(this));
autocomplete_edit_tracker_.reset(
new AutomationAutocompleteEditTracker(this));
new_tab_ui_load_observer_.reset(new NewTabUILoadObserver(this));
dom_operation_observer_.reset(new DomOperationMessageSender(this));
metric_event_duration_observer_.reset(new MetricEventDurationObserver());
extension_test_result_observer_.reset(
new ExtensionTestResultNotificationObserver(this));
g_browser_process->AddRefModule();
TRACE_EVENT_END("AutomationProvider::AutomationProvider", 0, "");
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 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: void doMergeNameDict(PDFDoc *doc, XRef *srcXRef, XRef *countRef, int oldRefNum, int newRefNum, Dict *srcNameDict, Dict *mergeNameDict, int numOffset) {
for (int i = 0; i < mergeNameDict->getLength(); i++) {
const char *key = mergeNameDict->getKey(i);
Object mergeNameTree;
Object srcNameTree;
mergeNameDict->lookup(key, &mergeNameTree);
srcNameDict->lookup(key, &srcNameTree);
if (srcNameTree.isDict() && mergeNameTree.isDict()) {
doMergeNameTree(doc, srcXRef, countRef, oldRefNum, newRefNum, srcNameTree.getDict(), mergeNameTree.getDict(), numOffset);
} else if (srcNameTree.isNull() && mergeNameTree.isDict()) {
Object *newNameTree = new Object();
newNameTree->initDict(srcXRef);
doMergeNameTree(doc, srcXRef, countRef, oldRefNum, newRefNum, newNameTree->getDict(), mergeNameTree.getDict(), numOffset);
srcNameDict->add(copyString(key), newNameTree);
}
srcNameTree.free();
mergeNameTree.free();
}
}
Commit Message:
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68 ||
(ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
Commit Message: avcodec/dnxhddec: Move mb height check out of non hr branch
Fixes: out of array access
Fixes: poc.dnxhd
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
enum AVAudioServiceType *ast;
int ac3info, acmod, lfeon, bsmod;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
sizeof(*ast));
if (!ast)
return AVERROR(ENOMEM);
ac3info = avio_rb24(pb);
bsmod = (ac3info >> 14) & 0x7;
acmod = (ac3info >> 11) & 0x7;
lfeon = (ac3info >> 10) & 0x1;
st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
if (lfeon)
st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
*ast = bsmod;
if (st->codecpar->channels > 1 && bsmod == 0x7)
*ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
st->codec->audio_service_type = *ast;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
return 0;
}
Commit Message: avformat/mov: Fix DoS in read_tfra()
Fixes: Missing EOF check in loop
No testcase
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: read_one_file(Image *image)
{
if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO))
{
/* memory or stdio. */
FILE *f = fopen(image->file_name, "rb");
if (f != NULL)
{
if (image->opts & READ_FILE)
image->input_file = f;
else /* memory */
{
if (fseek(f, 0, SEEK_END) == 0)
{
long int cb = ftell(f);
if (cb > 0 && (unsigned long int)cb < (size_t)~(size_t)0)
{
png_bytep b = voidcast(png_bytep, malloc((size_t)cb));
if (b != NULL)
{
rewind(f);
if (fread(b, (size_t)cb, 1, f) == 1)
{
fclose(f);
image->input_memory_size = cb;
image->input_memory = b;
}
else
{
free(b);
return logclose(image, f, image->file_name,
": read failed: ");
}
}
else
return logclose(image, f, image->file_name,
": out of memory: ");
}
else if (cb == 0)
return logclose(image, f, image->file_name,
": zero length: ");
else
return logclose(image, f, image->file_name,
": tell failed: ");
}
else
return logclose(image, f, image->file_name, ": seek failed: ");
}
}
else
return logerror(image, image->file_name, ": open failed: ",
strerror(errno));
}
return read_file(image, FORMAT_NO_CHANGE, NULL);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs, const char *lxcpath)
{
int ret;
size_t clen;
char *path;
INFO("Mounting container /dev");
/* $(rootfs->mount) + "/dev/pts" + '\0' */
clen = (rootfs->path ? strlen(rootfs->mount) : 0) + 9;
path = alloca(clen);
ret = snprintf(path, clen, "%s/dev", rootfs->path ? rootfs->mount : "");
if (ret < 0 || ret >= clen)
return -1;
if (!dir_exists(path)) {
WARN("No /dev in container.");
WARN("Proceeding without autodev setup");
return 0;
}
if (mount("none", path, "tmpfs", 0, "size=100000,mode=755")) {
SYSERROR("Failed mounting tmpfs onto %s\n", path);
return false;
}
INFO("Mounted tmpfs onto %s", path);
ret = snprintf(path, clen, "%s/dev/pts", rootfs->path ? rootfs->mount : "");
if (ret < 0 || ret >= clen)
return -1;
/*
* If we are running on a devtmpfs mapping, dev/pts may already exist.
* If not, then create it and exit if that fails...
*/
if (!dir_exists(path)) {
ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
if (ret) {
SYSERROR("Failed to create /dev/pts in container");
return -1;
}
}
INFO("Mounted container /dev");
return 0;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
Target: 1
Example 2:
Code: static int __init tcp_illinois_register(void)
{
BUILD_BUG_ON(sizeof(struct illinois) > ICSK_CA_PRIV_SIZE);
return tcp_register_congestion_control(&tcp_illinois);
}
Commit Message: net: fix divide by zero in tcp algorithm illinois
Reading TCP stats when using TCP Illinois congestion control algorithm
can cause a divide by zero kernel oops.
The division by zero occur in tcp_illinois_info() at:
do_div(t, ca->cnt_rtt);
where ca->cnt_rtt can become zero (when rtt_reset is called)
Steps to Reproduce:
1. Register tcp_illinois:
# sysctl -w net.ipv4.tcp_congestion_control=illinois
2. Monitor internal TCP information via command "ss -i"
# watch -d ss -i
3. Establish new TCP conn to machine
Either it fails at the initial conn, or else it needs to wait
for a loss or a reset.
This is only related to reading stats. The function avg_delay() also
performs the same divide, but is guarded with a (ca->cnt_rtt > 0) at its
calling point in update_params(). Thus, simply fix tcp_illinois_info().
Function tcp_illinois_info() / get_info() is called without
socket lock. Thus, eliminate any race condition on ca->cnt_rtt
by using a local stack variable. Simply reuse info.tcpv_rttcnt,
as its already set to ca->cnt_rtt.
Function avg_delay() is not affected by this race condition, as
its called with the socket lock.
Cc: Petr Matousek <[email protected]>
Signed-off-by: Jesper Dangaard Brouer <[email protected]>
Acked-by: Eric Dumazet <[email protected]>
Acked-by: Stephen Hemminger <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ip6mr_get_route(struct net *net, struct sk_buff *skb, struct rtmsg *rtm,
u32 portid)
{
int err;
struct mr6_table *mrt;
struct mfc6_cache *cache;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
mrt = ip6mr_get_table(net, RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
read_lock(&mrt_lock);
cache = ip6mr_cache_find(mrt, &rt->rt6i_src.addr, &rt->rt6i_dst.addr);
if (!cache && skb->dev) {
int vif = ip6mr_find_vif(mrt, skb->dev);
if (vif >= 0)
cache = ip6mr_cache_find_any(mrt, &rt->rt6i_dst.addr,
vif);
}
if (!cache) {
struct sk_buff *skb2;
struct ipv6hdr *iph;
struct net_device *dev;
int vif;
dev = skb->dev;
if (!dev || (vif = ip6mr_find_vif(mrt, dev)) < 0) {
read_unlock(&mrt_lock);
return -ENODEV;
}
/* really correct? */
skb2 = alloc_skb(sizeof(struct ipv6hdr), GFP_ATOMIC);
if (!skb2) {
read_unlock(&mrt_lock);
return -ENOMEM;
}
NETLINK_CB(skb2).portid = portid;
skb_reset_transport_header(skb2);
skb_put(skb2, sizeof(struct ipv6hdr));
skb_reset_network_header(skb2);
iph = ipv6_hdr(skb2);
iph->version = 0;
iph->priority = 0;
iph->flow_lbl[0] = 0;
iph->flow_lbl[1] = 0;
iph->flow_lbl[2] = 0;
iph->payload_len = 0;
iph->nexthdr = IPPROTO_NONE;
iph->hop_limit = 0;
iph->saddr = rt->rt6i_src.addr;
iph->daddr = rt->rt6i_dst.addr;
err = ip6mr_cache_unresolved(mrt, vif, skb2);
read_unlock(&mrt_lock);
return err;
}
if (rtm->rtm_flags & RTM_F_NOTIFY)
cache->mfc_flags |= MFC_NOTIFY;
err = __ip6mr_fill_mroute(mrt, skb, cache, rtm);
read_unlock(&mrt_lock);
return err;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,
struct nci_rf_intf_activated_ntf *ntf, __u8 *data)
{
struct activation_params_nfca_poll_iso_dep *nfca_poll;
struct activation_params_nfcb_poll_iso_dep *nfcb_poll;
switch (ntf->activation_rf_tech_and_mode) {
case NCI_NFC_A_PASSIVE_POLL_MODE:
nfca_poll = &ntf->activation_params.nfca_poll_iso_dep;
nfca_poll->rats_res_len = *data++;
pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len);
if (nfca_poll->rats_res_len > 0) {
memcpy(nfca_poll->rats_res,
data, nfca_poll->rats_res_len);
}
break;
case NCI_NFC_B_PASSIVE_POLL_MODE:
nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;
nfcb_poll->attrib_res_len = *data++;
pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len);
if (nfcb_poll->attrib_res_len > 0) {
memcpy(nfcb_poll->attrib_res,
data, nfcb_poll->attrib_res_len);
}
break;
default:
pr_err("unsupported activation_rf_tech_and_mode 0x%x\n",
ntf->activation_rf_tech_and_mode);
return NCI_STATUS_RF_PROTOCOL_ERROR;
}
return NCI_STATUS_OK;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebPagePrivate::applySizeOverride(int overrideWidth, int overrideHeight)
{
m_client->requestUpdateViewport(overrideWidth, overrideHeight);
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: streamMemParseTest(const char *filename, const char *result, const char *err,
int options) {
xmlTextReaderPtr reader;
int ret;
const char *base;
int size;
/*
* load and parse the memory
*/
if (loadMem(filename, &base, &size) != 0) {
fprintf(stderr, "Failed to load %s\n", filename);
return(-1);
}
reader = xmlReaderForMemory(base, size, filename, NULL, options);
ret = streamProcessTest(filename, result, err, reader, NULL, options);
free((char *)base);
xmlFreeTextReader(reader);
return(ret);
}
Commit Message: Fix handling of parameter-entity references
There were two bugs where parameter-entity references could lead to an
unexpected change of the input buffer in xmlParseNameComplex and
xmlDictLookup being called with an invalid pointer.
Percent sign in DTD Names
=========================
The NEXTL macro used to call xmlParserHandlePEReference. When parsing
"complex" names inside the DTD, this could result in entity expansion
which created a new input buffer. The fix is to simply remove the call
to xmlParserHandlePEReference from the NEXTL macro. This is safe because
no users of the macro require expansion of parameter entities.
- xmlParseNameComplex
- xmlParseNCNameComplex
- xmlParseNmtoken
The percent sign is not allowed in names, which are grammatical tokens.
- xmlParseEntityValue
Parameter-entity references in entity values are expanded but this
happens in a separate step in this function.
- xmlParseSystemLiteral
Parameter-entity references are ignored in the system literal.
- xmlParseAttValueComplex
- xmlParseCharDataComplex
- xmlParseCommentComplex
- xmlParsePI
- xmlParseCDSect
Parameter-entity references are ignored outside the DTD.
- xmlLoadEntityContent
This function is only called from xmlStringLenDecodeEntities and
entities are replaced in a separate step immediately after the function
call.
This bug could also be triggered with an internal subset and double
entity expansion.
This fixes bug 766956 initially reported by Wei Lei and independently by
Chromium's ClusterFuzz, Hanno Böck, and Marco Grassi. Thanks to everyone
involved.
xmlParseNameComplex with XML_PARSE_OLD10
========================================
When parsing Names inside an expanded parameter entity with the
XML_PARSE_OLD10 option, xmlParseNameComplex would call xmlGROW via the
GROW macro if the input buffer was exhausted. At the end of the
parameter entity's replacement text, this function would then call
xmlPopInput which invalidated the input buffer.
There should be no need to invoke GROW in this situation because the
buffer is grown periodically every XML_PARSER_CHUNK_SIZE characters and,
at least for UTF-8, in xmlCurrentChar. This also matches the code path
executed when XML_PARSE_OLD10 is not set.
This fixes bugs 781205 (CVE-2017-9049) and 781361 (CVE-2017-9050).
Thanks to Marcel Böhme and Thuan Pham for the report.
Additional hardening
====================
A separate check was added in xmlParseNameComplex to validate the
buffer size.
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: ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static struct sock *__rfcomm_get_listen_sock_by_addr(u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL;
sk_for_each(sk, &rfcomm_sk_list.head) {
if (rfcomm_pi(sk)->channel != channel)
continue;
if (bacmp(&rfcomm_pi(sk)->src, src))
continue;
if (sk->sk_state == BT_BOUND || sk->sk_state == BT_LISTEN)
break;
}
return sk ? sk : NULL;
}
Commit Message: Bluetooth: Fix potential NULL dereference in RFCOMM bind callback
addr can be NULL and it should not be dereferenced before NULL checking.
Signed-off-by: Jaganath Kanakkassery <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu) ||
!nested_vmx_check_vmcs12(vcpu))
return 1;
/* Decode instruction info and find the field to read */
field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (!vmcs12_read_any(vcpu, field, &field_value)) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
skip_emulated_instruction(vcpu);
return 1;
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, &gva))
return 1;
/* _system ok, as nested_vmx_check_permission verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
Commit Message: nEPT: Nested INVEPT
If we let L1 use EPT, we should probably also support the INVEPT instruction.
In our current nested EPT implementation, when L1 changes its EPT table
for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in
the course of this modification already calls INVEPT. But if last level
of shadow page is unsync not all L1's changes to EPT12 are intercepted,
which means roots need to be synced when L1 calls INVEPT. Global INVEPT
should not be different since roots are synced by kvm_mmu_load() each
time EPTP02 changes.
Reviewed-by: Xiao Guangrong <[email protected]>
Signed-off-by: Nadav Har'El <[email protected]>
Signed-off-by: Jun Nakajima <[email protected]>
Signed-off-by: Xinhao Xu <[email protected]>
Signed-off-by: Yang Zhang <[email protected]>
Signed-off-by: Gleb Natapov <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.