prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
{
unsigned long *msr_bitmap;
if (is_guest_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_nested;
else if (vcpu->arch.apic_base & X2APIC_ENABLE) {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode;
else
msr_bitmap = vmx_msr_bitmap_legacy;
}
vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
}
Commit Message: kvm:vmx: more complete state update on APICv on/off
The function to update APICv on/off state (in particular, to deactivate
it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust
APICv-related fields among secondary processor-based VM-execution
controls. As a result, Windows 2012 guests get stuck when SynIC-based
auto-EOI interrupt intersected with e.g. an IPI in the guest.
In addition, the MSR intercept bitmap isn't updated every time "virtualize
x2APIC mode" is toggled. This path can only be triggered by a malicious
guest, because Windows didn't use x2APIC but rather their own synthetic
APIC access MSRs; however a guest running in a SynIC-enabled VM could
switch to x2APIC and thus obtain direct access to host APIC MSRs
(CVE-2016-4440).
The patch fixes those omissions.
Signed-off-by: Roman Kagan <[email protected]>
Reported-by: Steve Rutherford <[email protected]>
Reported-by: Yang Zhang <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: mrb_define_class_method(mrb_state *mrb, struct RClass *c, const char *name, mrb_func_t func, mrb_aspec aspec)
{
mrb_define_singleton_method(mrb, (struct RObject*)c, name, func, aspec);
}
Commit Message: `mrb_class_real()` did not work for `BasicObject`; fix #4037
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: int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
{
int r;
mutex_lock(&kvm->slots_lock);
r = __x86_set_memory_region(kvm, id, gpa, size);
mutex_unlock(&kvm->slots_lock);
return r;
}
Commit Message: KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = ext4_inode_aio(inode);
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical "
"block %llu, max_blocks %u, flags %x, allocated %u\n",
inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
flags, allocated);
ext4_ext_show_leaf(inode, path);
trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
newblock);
/* get_block() before submit the IO, split the extent */
if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
ret = ext4_split_unwritten_extents(handle, inode, map,
path, flags);
if (ret <= 0)
goto out;
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to conversion to written when IO is
* completed
*/
if (io)
ext4_set_io_unwritten_flag(inode, io);
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
if (ext4_should_dioread_nolock(inode))
map->m_flags |= EXT4_MAP_UNINIT;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
ret = ext4_convert_unwritten_extents_endio(handle, inode,
path);
if (ret >= 0) {
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, map->m_len);
} else
err = ret;
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > map->m_len) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + map->m_len,
allocated - map->m_len);
allocated = map->m_len;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
unsigned int reserved_clusters;
reserved_clusters = get_reserved_cluster_alloc(inode,
map->m_lblk, map->m_len);
if (reserved_clusters)
ext4_da_update_reserve_space(inode,
reserved_clusters,
0);
}
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
map->m_len);
if (err < 0)
goto out2;
}
out1:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_pblk = newblock;
map->m_len = allocated;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-362
Target: 1
Example 2:
Code: int kvm_arch_hardware_setup(void)
{
int r;
r = kvm_x86_ops->hardware_setup();
if (r != 0)
return r;
if (kvm_has_tsc_control) {
/*
* Make sure the user can only configure tsc_khz values that
* fit into a signed integer.
* A min value is not calculated needed because it will always
* be 1 on all machines.
*/
u64 max = min(0x7fffffffULL,
__scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
kvm_max_guest_tsc_khz = max;
kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
}
kvm_init_msr_list();
return 0;
}
Commit Message: KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[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: png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_pHYs_SUPPORTED
if (info_ptr->valid & PNG_INFO_pHYs)
{
png_debug1(1, "in %s retrieval function", "png_get_pixels_per_meter");
if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
return (0);
else
return (info_ptr->x_pixels_per_unit);
}
#else
return (0);
#endif
return (0);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
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: MockRenderProcess::MockRenderProcess()
: transport_dib_next_sequence_number_(0) {
}
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 nfsd4_mach_creds_match(struct nfs4_client *cl, struct svc_rqst *rqstp)
{
struct svc_cred *cr = &rqstp->rq_cred;
if (!cl->cl_mach_cred)
return true;
if (cl->cl_cred.cr_gss_mech != cr->cr_gss_mech)
return false;
if (!svc_rqst_integrity_protected(rqstp))
return false;
if (cl->cl_cred.cr_raw_principal)
return 0 == strcmp(cl->cl_cred.cr_raw_principal,
cr->cr_raw_principal);
if (!cr->cr_principal)
return false;
return 0 == strcmp(cl->cl_cred.cr_principal, cr->cr_principal);
}
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 RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
TRACE_EVENT2("navigation", "RenderFrameHostImpl::OnDidStartLoading",
"frame_tree_node", frame_tree_node_->frame_tree_node_id(),
"to different document", to_different_document);
if (to_different_document) {
bad_message::ReceivedBadMessage(GetProcess(),
bad_message::RFH_UNEXPECTED_LOAD_START);
return;
}
bool was_previously_loading = frame_tree_node_->frame_tree()->IsLoading();
is_loading_ = true;
if (is_active()) {
frame_tree_node_->DidStartLoading(to_different_document,
was_previously_loading);
}
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (chromeos::ChangeInputMethod(input_method_status_connection_,
input_method_id_to_switch.c_str())) {
return true;
}
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
assert((cc0%rowsize)==0);
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
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: AP_DECLARE(int) ap_process_request_internal(request_rec *r)
{
int file_req = (r->main && r->filename);
int access_status;
core_dir_config *d;
/* Ignore embedded %2F's in path for proxy requests */
if (!r->proxyreq && r->parsed_uri.path) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->allow_encoded_slashes) {
access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes);
}
else {
access_status = ap_unescape_url(r->parsed_uri.path);
}
if (access_status) {
if (access_status == HTTP_NOT_FOUND) {
if (! d->allow_encoded_slashes) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026)
"found %%2f (encoded '/') in URI "
"(decoded='%s'), returning 404",
r->parsed_uri.path);
}
}
return access_status;
}
}
ap_getparents(r->uri); /* OK --- shrinking transformations... */
/* All file subrequests are a huge pain... they cannot bubble through the
* next several steps. Only file subrequests are allowed an empty uri,
* otherwise let translate_name kill the request.
*/
if (!file_req) {
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_translate_name(r))) {
return decl_die(access_status, "translate", r);
}
}
/* Reset to the server default config prior to running map_to_storage
*/
r->per_dir_config = r->server->lookup_defaults;
if ((access_status = ap_run_map_to_storage(r))) {
/* This request wasn't in storage (e.g. TRACE) */
return access_status;
}
/* Rerun the location walk, which overrides any map_to_storage config.
*/
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_post_perdir_config(r))) {
return access_status;
}
/* Only on the main request! */
if (r->main == NULL) {
if ((access_status = ap_run_header_parser(r))) {
return access_status;
}
}
/* Skip authn/authz if the parent or prior request passed the authn/authz,
* and that configuration didn't change (this requires optimized _walk()
* functions in map_to_storage that use the same merge results given
* identical input.) If the config changes, we must re-auth.
*/
if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
r->user = r->prev->user;
r->ap_auth_type = r->prev->ap_auth_type;
}
else if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
r->user = r->main->user;
r->ap_auth_type = r->main->ap_auth_type;
}
else {
switch (ap_satisfies(r)) {
case SATISFY_ALL:
case SATISFY_NOSPEC:
if ((access_status = ap_run_access_checker(r)) != OK) {
return decl_die(access_status,
"check access (with Satisfy All)", r);
}
access_status = ap_run_access_checker_ex(r);
if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else if (access_status != DECLINED) {
return decl_die(access_status, "check access", r);
}
else {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
break;
case SATISFY_ANY:
if ((access_status = ap_run_access_checker(r)) == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker hook and 'Satisfy any': %s",
r->uri);
break;
}
access_status = ap_run_access_checker_ex(r);
if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else if (access_status != DECLINED) {
return decl_die(access_status, "check access", r);
}
else {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
break;
}
}
/* XXX Must make certain the ap_run_type_checker short circuits mime
* in mod-proxy for r->proxyreq && r->parsed_uri.scheme
* && !strcmp(r->parsed_uri.scheme, "http")
*/
if ((access_status = ap_run_type_checker(r)) != OK) {
return decl_die(access_status, "find types", r);
}
if ((access_status = ap_run_fixups(r)) != OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s",
access_status, r->uri);
return access_status;
}
return OK;
}
Commit Message: SECURITY: CVE-2015-3183 (cve.mitre.org)
Replacement of ap_some_auth_required (unusable in Apache httpd 2.4)
with new ap_some_authn_required and ap_force_authn hook.
Submitted by: breser
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264
Target: 1
Example 2:
Code: xsltCleanupTemplates(xsltStylesheetPtr style ATTRIBUTE_UNUSED) {
}
Commit Message: Handle a bad XSLT expression better.
BUG=138672
Review URL: https://chromiumcodereview.appspot.com/10830177
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@150123 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER)
dev = alloc_netdev(0, "pvceth%d", ether_setup);
else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
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: | 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: unsigned int subpel_avg_variance_ref(const uint8_t *ref,
const uint8_t *src,
const uint8_t *second_pred,
int l2w, int l2h,
int xoff, int yoff,
unsigned int *sse_ptr) {
int se = 0;
unsigned int sse = 0;
const int w = 1 << l2w, h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x];
se += diff;
sse += diff * diff;
}
}
*sse_ptr = sse;
return sse - (((int64_t) se * se) >> (l2w + l2h));
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AddExtensionAndGrantPermissions(const Extension& extension) {
PermissionsUpdater updater(profile());
updater.InitializePermissions(&extension);
updater.GrantActivePermissions(&extension);
service()->AddExtension(&extension);
}
Commit Message: [Extensions] Have URLPattern::Contains() properly check schemes
Have URLPattern::Contains() properly check the schemes of the patterns
when evaluating if one pattern contains another. This is important in
order to prevent extensions from requesting chrome:-scheme permissions
via the permissions API when <all_urls> is specified as an optional
permission.
Bug: 859600,918470
Change-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d
Reviewed-on: https://chromium-review.googlesource.com/c/1396561
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621410}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionSerializedValue(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"));
RefPtr<SerializedScriptValue> serializedArg(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->serializedValue(serializedArg);
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
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: CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
handle.parent_client_id = context_->GetChannelID();
handle.parent_context_id = context_->GetContextID();
handle.parent_texture_id[0] = context_->createTexture();
handle.parent_texture_id[1] = context_->createTexture();
handle.sync_point = context_->insertSyncPoint();
context_->flush();
return handle;
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static int em_loop(struct x86_emulate_ctxt *ctxt)
{
register_address_increment(ctxt, &ctxt->regs[VCPU_REGS_RCX], -1);
if ((address_mask(ctxt, ctxt->regs[VCPU_REGS_RCX]) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: fix missing checks in syscall emulation
On hosts without this patch, 32bit guests will crash (and 64bit guests
may behave in a wrong way) for example by simply executing following
nasm-demo-application:
[bits 32]
global _start
SECTION .text
_start: syscall
(I tested it with winxp and linux - both always crashed)
Disassembly of section .text:
00000000 <_start>:
0: 0f 05 syscall
The reason seems a missing "invalid opcode"-trap (int6) for the
syscall opcode "0f05", which is not available on Intel CPUs
within non-longmodes, as also on some AMD CPUs within legacy-mode.
(depending on CPU vendor, MSR_EFER and cpuid)
Because previous mentioned OSs may not engage corresponding
syscall target-registers (STAR, LSTAR, CSTAR), they remain
NULL and (non trapping) syscalls are leading to multiple
faults and finally crashs.
Depending on the architecture (AMD or Intel) pretended by
guests, various checks according to vendor's documentation
are implemented to overcome the current issue and behave
like the CPUs physical counterparts.
[mtosatti: cleanup/beautify code]
Signed-off-by: Stephan Baerwolf <[email protected]>
Signed-off-by: Marcelo Tosatti <[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: int Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
effect_param_t *p = (effect_param_t *)pCmdData;
if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
cmdSize < (sizeof(effect_param_t) + p->psize) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(effect_param_t) + p->psize)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
(size_t *)&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
Commit Message: fix possible overflow in effect wrappers.
Add checks on parameter size field in effect command handlers
to avoid overflow leading to invalid comparison with min allowed
size for command and reply buffers.
Bug: 26347509.
Change-Id: I20e6a9b6de8e5172b957caa1ac9410b9752efa4d
(cherry picked from commit ad1bd92a49d78df6bc6e75bee68c517c1326f3cf)
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 print_value(int output, int num, const char *devname,
const char *value, const char *name, size_t valsz)
{
if (output & OUTPUT_VALUE_ONLY) {
fputs(value, stdout);
fputc('\n', stdout);
} else if (output & OUTPUT_UDEV_LIST) {
print_udev_format(name, value);
} else if (output & OUTPUT_EXPORT_LIST) {
if (num == 1 && devname)
printf("DEVNAME=%s\n", devname);
fputs(name, stdout);
fputs("=", stdout);
safe_print(value, valsz, NULL);
fputs("\n", stdout);
} else {
if (num == 1 && devname)
printf("%s:", devname);
fputs(" ", stdout);
fputs(name, stdout);
fputs("=\"", stdout);
safe_print(value, valsz, "\"");
fputs("\"", stdout);
}
}
Commit Message: libblkid: care about unsafe chars in cache
The high-level libblkid API uses /run/blkid/blkid.tab cache to
store probing results. The cache format is
<device NAME="value" ...>devname</device>
and unfortunately the cache code does not escape quotation marks:
# mkfs.ext4 -L 'AAA"BBB'
# cat /run/blkid/blkid.tab
...
<device ... LABEL="AAA"BBB" ...>/dev/sdb1</device>
such string is later incorrectly parsed and blkid(8) returns
nonsenses. And for use-cases like
# eval $(blkid -o export /dev/sdb1)
it's also insecure.
Note that mount, udevd and blkid -p are based on low-level libblkid
API, it bypass the cache and directly read data from the devices.
The current udevd upstream does not depend on blkid(8) output at all,
it's directly linked with the library and all unsafe chars are encoded by
\x<hex> notation.
# mkfs.ext4 -L 'X"`/tmp/foo` "' /dev/sdb1
# udevadm info --export-db | grep LABEL
...
E: ID_FS_LABEL=X__/tmp/foo___
E: ID_FS_LABEL_ENC=X\x22\x60\x2ftmp\x2ffoo\x60\x20\x22
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-77
Target: 1
Example 2:
Code: static int lua_ap_expr(lua_State *L)
{
request_rec *r;
int x = 0;
const char *expr,
*err;
ap_expr_info_t res;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
expr = lua_tostring(L, 2);
res.filename = NULL;
res.flags = 0;
res.line_number = 0;
res.module_index = APLOG_MODULE_INDEX;
err = ap_expr_parse(r->pool, r->pool, &res, expr, NULL);
if (!err) {
x = ap_expr_exec(r, &res, &err);
lua_pushboolean(L, x);
if (x < 0) {
lua_pushstring(L, err);
return 2;
}
return 1;
} else {
lua_pushboolean(L, 0);
lua_pushstring(L, err);
return 2;
}
lua_pushboolean(L, 0);
return 1;
}
Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org)
mod_lua: A maliciously crafted websockets PING after a script
calls r:wsupgrade() can cause a child process crash.
[Edward Lu <Chaosed0 gmail.com>]
Discovered by Guido Vranken <guidovranken gmail.com>
Submitted by: Edward Lu
Committed by: covener
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68
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: wifi_error wifi_set_scanning_mac_oui(wifi_interface_handle handle, oui scan_oui)
{
SetPnoMacAddrOuiCommand command(handle, scan_oui);
return (wifi_error)command.start();
}
Commit Message: Fix use-after-free in wifi_cleanup()
Release reference to cmd only after possibly calling getType().
BUG: 25753768
Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb
(cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223)
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
const size_t data_size)
{
#define MaxCode(number_bits) ((one << (number_bits))-1)
#define MaxHashTable 5003
#define MaxGIFBits 12UL
#define MaxGIFTable (1UL << MaxGIFBits)
#define GIFOutputCode(code) \
{ \
/* \
Emit a code. \
*/ \
if (bits > 0) \
datum|=(size_t) (code) << bits; \
else \
datum=(size_t) (code); \
bits+=number_bits; \
while (bits >= 8) \
{ \
/* \
Add a character to current packet. \
*/ \
packet[length++]=(unsigned char) (datum & 0xff); \
if (length >= 254) \
{ \
(void) WriteBlobByte(image,(unsigned char) length); \
(void) WriteBlob(image,length,packet); \
length=0; \
} \
datum>>=8; \
bits-=8; \
} \
if (free_code > max_code) \
{ \
number_bits++; \
if (number_bits == MaxGIFBits) \
max_code=MaxGIFTable; \
else \
max_code=MaxCode(number_bits); \
} \
}
IndexPacket
index;
short
*hash_code,
*hash_prefix,
waiting_code;
size_t
bits,
clear_code,
datum,
end_of_information_code,
free_code,
length,
max_code,
next_pixel,
number_bits,
one,
pass;
ssize_t
displacement,
offset,
k,
y;
unsigned char
*packet,
*hash_suffix;
/*
Allocate encoder tables.
*/
assert(image != (Image *) NULL);
one=1;
packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
sizeof(*hash_suffix));
if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
(hash_prefix == (short *) NULL) ||
(hash_suffix == (unsigned char *) NULL))
{
if (packet != (unsigned char *) NULL)
packet=(unsigned char *) RelinquishMagickMemory(packet);
if (hash_code != (short *) NULL)
hash_code=(short *) RelinquishMagickMemory(hash_code);
if (hash_prefix != (short *) NULL)
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
if (hash_suffix != (unsigned char *) NULL)
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
return(MagickFalse);
}
/*
Initialize GIF encoder.
*/
(void) memset(packet,0,256*sizeof(*packet));
(void) memset(hash_code,0,MaxHashTable*sizeof(*hash_code));
(void) memset(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix));
(void) memset(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix));
number_bits=data_size;
max_code=MaxCode(number_bits);
clear_code=((short) one << (data_size-1));
end_of_information_code=clear_code+1;
free_code=clear_code+2;
length=0;
datum=0;
bits=0;
GIFOutputCode(clear_code);
/*
Encode pixels.
*/
offset=0;
pass=0;
waiting_code=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,offset,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
if (y == 0)
{
waiting_code=(short) (*indexes);
p++;
}
for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++)
{
/*
Probe hash table.
*/
index=(IndexPacket) ((size_t) GetPixelIndex(indexes+x) & 0xff);
p++;
k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code);
if (k >= MaxHashTable)
k-=MaxHashTable;
next_pixel=MagickFalse;
displacement=1;
if (hash_code[k] > 0)
{
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
continue;
}
if (k != 0)
displacement=MaxHashTable-k;
for ( ; ; )
{
k-=displacement;
if (k < 0)
k+=MaxHashTable;
if (hash_code[k] == 0)
break;
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
next_pixel=MagickTrue;
break;
}
}
if (next_pixel != MagickFalse)
continue;
}
GIFOutputCode(waiting_code);
if (free_code < MaxGIFTable)
{
hash_code[k]=(short) free_code++;
hash_prefix[k]=waiting_code;
hash_suffix[k]=(unsigned char) index;
}
else
{
/*
Fill the hash table with empty entries.
*/
for (k=0; k < MaxHashTable; k++)
hash_code[k]=0;
/*
Reset compressor and issue a clear code.
*/
free_code=clear_code+2;
GIFOutputCode(clear_code);
number_bits=data_size;
max_code=MaxCode(number_bits);
}
waiting_code=(short) index;
}
if (image_info->interlace == NoInterlace)
offset++;
else
switch (pass)
{
case 0:
default:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=4;
}
break;
}
case 1:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=2;
}
break;
}
case 2:
{
offset+=4;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=1;
}
break;
}
case 3:
{
offset+=2;
break;
}
}
}
/*
Flush out the buffered code.
*/
GIFOutputCode(waiting_code);
GIFOutputCode(end_of_information_code);
if (bits > 0)
{
/*
Add a character to current packet.
*/
packet[length++]=(unsigned char) (datum & 0xff);
if (length >= 254)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
length=0;
}
}
/*
Flush accumulated data.
*/
if (length > 0)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
}
/*
Free encoder memory.
*/
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
hash_code=(short *) RelinquishMagickMemory(hash_code);
packet=(unsigned char *) RelinquishMagickMemory(packet);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595
CWE ID: CWE-119
Target: 1
Example 2:
Code: explicit IteratorImpl(base::WeakPtr<InFlightBackendIO> background_queue)
: background_queue_(background_queue),
iterator_(new Rankings::Iterator()) {
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
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: gboolean BrowserWindowGtk::OnGtkAccelerator(GtkAccelGroup* accel_group,
GObject* acceleratable,
guint keyval,
GdkModifierType modifier,
void* user_data) {
int command_id = GPOINTER_TO_INT(user_data);
BrowserWindowGtk* browser_window =
GetBrowserWindowForNativeWindow(GTK_WINDOW(acceleratable));
DCHECK(browser_window != NULL);
return chrome::ExecuteCommand(browser_window->browser(), command_id);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::ConfirmPairing() {
if (!agent_.get() || confirmation_callback_.is_null())
return;
confirmation_callback_.Run(SUCCESS);
confirmation_callback_.Reset();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: R_API RFlagItem *r_flag_get_at(RFlag *f, ut64 off, bool closest) {
RFlagItem *item, *nice = NULL;
RListIter *iter;
const RFlagsAtOffset *flags_at = r_flag_get_nearest_list (f, off, -1);
if (!flags_at) {
return NULL;
}
if (flags_at->off == off) {
r_list_foreach (flags_at->flags, iter, item) {
if (f->space_idx != -1 && item->space != f->space_idx) {
continue;
}
if (nice) {
if (isFunctionFlag (nice->name)) {
nice = item;
}
} else {
nice = item;
}
}
return nice;
}
if (!closest) {
return NULL;
}
while (!nice && flags_at) {
r_list_foreach (flags_at->flags, iter, item) {
if (f->space_strict && IS_IN_SPACE (f, item)) {
continue;
}
if (item->offset == off) {
eprintf ("XXX Should never happend\n");
return evalFlag (f, item);
}
nice = item;
break;
}
if (flags_at->off) {
flags_at = r_flag_get_nearest_list (f, flags_at->off - 1, -1);
} else {
flags_at = NULL;
}
}
return evalFlag (f, nice);
}
Commit Message: Fix crash in wasm disassembler
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int fz_colorspace_is_gray(fz_context *ctx, const fz_colorspace *cs)
{
return cs && cs->type == FZ_COLORSPACE_GRAY;
}
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: void SynchronousCompositorOutputSurface::InvokeComposite(
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
gfx::Transform transform_for_tile_priority,
bool hardware_draw) {
DCHECK(!frame_holder_.get());
gfx::Transform adjusted_transform = transform;
adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0);
SetExternalDrawConstraints(adjusted_transform, viewport, clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority, !hardware_draw);
if (!hardware_draw || next_hardware_draw_needs_damage_) {
next_hardware_draw_needs_damage_ = false;
SetNeedsRedrawRect(gfx::Rect(viewport.size()));
}
client_->OnDraw();
if (hardware_draw) {
cached_hw_transform_ = adjusted_transform;
cached_hw_viewport_ = viewport;
cached_hw_clip_ = clip;
cached_hw_viewport_rect_for_tile_priority_ =
viewport_rect_for_tile_priority;
cached_hw_transform_for_tile_priority_ = transform_for_tile_priority;
} else {
bool resourceless_software_draw = false;
SetExternalDrawConstraints(cached_hw_transform_,
cached_hw_viewport_,
cached_hw_clip_,
cached_hw_viewport_rect_for_tile_priority_,
cached_hw_transform_for_tile_priority_,
resourceless_software_draw);
next_hardware_draw_needs_damage_ = true;
}
if (frame_holder_.get())
client_->DidSwapBuffersComplete();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static struct posix_acl *ocfs2_get_acl_nolock(struct inode *inode,
int type,
struct buffer_head *di_bh)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index,
"", value, retval);
}
if (retval > 0)
acl = ocfs2_acl_from_xattr(value, retval);
else if (retval == -ENODATA || retval == 0)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 TabStripModel::IsTabBlocked(int index) const {
return contents_data_[index]->blocked;
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
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: bool TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
base::subtle::AutoWriteLock task_lock(task_lock_);
return true;
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ~FPDF_SYSFONTINFO_WITHMETRICS() {
FPDF_FreeDefaultSystemFontInfo(default_sysfontinfo);
}
Commit Message: [pdf] Use a temporary list when unloading pages
When traversing the |deferred_page_unloads_| list and handling the
unloads it's possible for new pages to get added to the list which will
invalidate the iterator.
This CL swaps the list with an empty list and does the iteration on the
list copy. New items that are unloaded while handling the defers will be
unloaded at a later point.
Bug: 780450
Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac
Reviewed-on: https://chromium-review.googlesource.com/758916
Commit-Queue: dsinclair <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#515056}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 x86_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This generic handler doesn't seem to have any issues where the
* unmasking occurs so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
if (!test_bit(idx, cpuc->active_mask)) {
/*
* Though we deactivated the counter some cpus
* might still deliver spurious interrupts still
* in flight. Catch them:
*/
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
val = x86_perf_event_update(event);
if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
continue;
/*
* event overflow
*/
handled++;
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, 1, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
return handled;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParse3986Port(xmlURIPtr uri, const char **str)
{
const char *cur = *str;
unsigned port = 0; /* unsigned for defined overflow behavior */
if (ISA_DIGIT(cur)) {
while (ISA_DIGIT(cur)) {
port = port * 10 + (*cur - '0');
cur++;
}
if (uri != NULL)
uri->port = port & INT_MAX; /* port value modulo INT_MAX+1 */
*str = cur;
return(0);
}
return(1);
}
Commit Message: DO NOT MERGE: Use correct limit for port values
no upstream report yet, add it here when we have it
issue found & patch by nmehta@
Bug: 36555370
Change-Id: Ibf1efea554b95f514e23e939363d608021de4614
(cherry picked from commit b62884fb49fe92081e414966d9b5fe58250ae53c)
CWE ID: CWE-119
Target: 1
Example 2:
Code: ~RemoveDownloadsTester() { chrome_download_manager_delegate_.Shutdown(); }
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
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 int uvesafb_init(void)
{
int err;
#ifndef MODULE
char *option = NULL;
if (fb_get_options("uvesafb", &option))
return -ENODEV;
uvesafb_setup(option);
#endif
err = cn_add_callback(&uvesafb_cn_id, "uvesafb", uvesafb_cn_callback);
if (err)
return err;
err = platform_driver_register(&uvesafb_driver);
if (!err) {
uvesafb_device = platform_device_alloc("uvesafb", 0);
if (uvesafb_device)
err = platform_device_add(uvesafb_device);
else
err = -ENOMEM;
if (err) {
platform_device_put(uvesafb_device);
platform_driver_unregister(&uvesafb_driver);
cn_del_callback(&uvesafb_cn_id);
return err;
}
err = driver_create_file(&uvesafb_driver.driver,
&driver_attr_v86d);
if (err) {
pr_warn("failed to register attributes\n");
err = 0;
}
}
return err;
}
Commit Message: video: uvesafb: Fix integer overflow in allocation
cmap->len can get close to INT_MAX/2, allowing for an integer overflow in
allocation. This uses kmalloc_array() instead to catch the condition.
Reported-by: Dr Silvio Cesare of InfoSect <[email protected]>
Fixes: 8bdb3a2d7df48 ("uvesafb: the driver core")
Cc: [email protected]
Signed-off-by: Kees Cook <[email protected]>
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: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: T42_Face_Init( FT_Stream stream,
FT_Face t42face, /* T42_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
T42_Face face = (T42_Face)t42face;
FT_Error error;
FT_Service_PsCMaps psnames;
PSAux_Service psaux;
FT_Face root = (FT_Face)&face->root;
T1_Font type1 = &face->type1;
PS_FontInfo info = &type1->font_info;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_UNUSED( stream );
face->ttf_face = NULL;
face->root.num_faces = 1;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
face->psnames = psnames;
face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"psaux" );
psaux = (PSAux_Service)face->psaux;
if ( !psaux )
{
FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
FT_TRACE2(( "Type 42 driver\n" ));
/* open the tokenizer, this will also check the font format */
error = T42_Open_Face( face );
if ( error )
goto Exit;
/* if we just wanted to check the format, leave successfully now */
if ( face_index < 0 )
goto Exit;
/* check the face index */
if ( face_index > 0 )
{
FT_ERROR(( "T42_Face_Init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* Now load the font program into the face object */
/* Init the face object fields */
/* Now set up root face fields */
root->num_glyphs = type1->num_glyphs;
root->num_charmaps = 0;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_SCALABLE |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_GLYPH_NAMES;
if ( info->is_fixed_pitch )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
/* We only set this flag if we have the patented bytecode interpreter. */
/* There are no known `tricky' Type42 fonts that could be loaded with */
/* the unpatented interpreter. */
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
root->face_flags |= FT_FACE_FLAG_HINTER;
#endif
/* XXX: TODO -- add kerning with .afm support */
/* get style name -- be careful, some broken fonts only */
/* have a `/FontName' dictionary entry! */
root->family_name = info->family_name;
/* assume "Regular" style if we don't know better */
root->style_name = (char *)"Regular";
if ( root->family_name )
{
char* full = info->full_name;
char* family = root->family_name;
if ( full )
{
while ( *full )
{
if ( *full == *family )
{
family++;
full++;
}
else
{
if ( *full == ' ' || *full == '-' )
full++;
else if ( *family == ' ' || *family == '-' )
family++;
else
{
if ( !*family )
root->style_name = full;
break;
}
}
}
}
}
else
{
/* do we have a `/FontName'? */
if ( type1->font_name )
root->family_name = type1->font_name;
}
/* no embedded bitmap support */
root->num_fixed_sizes = 0;
root->available_sizes = 0;
/* Load the TTF font embedded in the T42 font */
{
FT_Open_Args args;
args.flags = FT_OPEN_MEMORY;
args.memory_base = face->ttf_data;
args.memory_size = face->ttf_size;
if ( num_params )
{
args.flags |= FT_OPEN_PARAMS;
args.num_params = num_params;
args.params = params;
}
error = FT_Open_Face( FT_FACE_LIBRARY( face ),
&args, 0, &face->ttf_face );
}
if ( error )
goto Exit;
FT_Done_Size( face->ttf_face->size );
/* Ignore info in FontInfo dictionary and use the info from the */
/* loaded TTF font. The PostScript interpreter also ignores it. */
root->bbox = face->ttf_face->bbox;
root->units_per_EM = face->ttf_face->units_per_EM;
root->ascender = face->ttf_face->ascender;
root->descender = face->ttf_face->descender;
root->height = face->ttf_face->height;
root->max_advance_width = face->ttf_face->max_advance_width;
root->max_advance_height = face->ttf_face->max_advance_height;
root->underline_position = (FT_Short)info->underline_position;
root->underline_thickness = (FT_Short)info->underline_thickness;
/* compute style flags */
root->style_flags = 0;
if ( info->italic_angle )
root->style_flags |= FT_STYLE_FLAG_ITALIC;
if ( face->ttf_face->style_flags & FT_STYLE_FLAG_BOLD )
root->style_flags |= FT_STYLE_FLAG_BOLD;
if ( face->ttf_face->face_flags & FT_FACE_FLAG_VERTICAL )
root->face_flags |= FT_FACE_FLAG_VERTICAL;
{
if ( psnames )
{
FT_CharMapRec charmap;
T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes;
FT_CMap_Class clazz;
charmap.face = root;
/* first of all, try to synthesize a Unicode charmap */
charmap.platform_id = TT_PLATFORM_MICROSOFT;
charmap.encoding_id = TT_MS_ID_UNICODE_CS;
charmap.encoding = FT_ENCODING_UNICODE;
error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL );
if ( error &&
FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) )
goto Exit;
error = FT_Err_Ok;
/* now, generate an Adobe Standard encoding when appropriate */
charmap.platform_id = TT_PLATFORM_ADOBE;
clazz = NULL;
switch ( type1->encoding_type )
{
case T1_ENCODING_TYPE_STANDARD:
charmap.encoding = FT_ENCODING_ADOBE_STANDARD;
charmap.encoding_id = TT_ADOBE_ID_STANDARD;
clazz = cmap_classes->standard;
break;
case T1_ENCODING_TYPE_EXPERT:
charmap.encoding = FT_ENCODING_ADOBE_EXPERT;
charmap.encoding_id = TT_ADOBE_ID_EXPERT;
clazz = cmap_classes->expert;
break;
case T1_ENCODING_TYPE_ARRAY:
charmap.encoding = FT_ENCODING_ADOBE_CUSTOM;
charmap.encoding_id = TT_ADOBE_ID_CUSTOM;
clazz = cmap_classes->custom;
break;
case T1_ENCODING_TYPE_ISOLATIN1:
charmap.encoding = FT_ENCODING_ADOBE_LATIN_1;
charmap.encoding_id = TT_ADOBE_ID_LATIN_1;
clazz = cmap_classes->unicode;
break;
default:
;
}
if ( clazz )
error = FT_CMap_New( clazz, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if ( root->num_charmaps )
root->charmap = root->charmaps[0];
#endif
}
}
Exit:
return error;
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
bool started) {
TRACE_EVENT_ASYNC_END0("net", "URLRequest", request);
if (request->status().status() == net::URLRequestStatus::SUCCESS) {
int64 received_content_length = request->received_response_content_length();
bool is_http = request->url().SchemeIs("http");
bool is_https = request->url().SchemeIs("https");
if (!request->was_cached() && // Don't record cached content
received_content_length && // Zero-byte responses aren't useful.
(is_http || is_https)) { // Only record for HTTP or HTTPS urls.
int64 original_content_length =
request->response_info().headers->GetInt64HeaderValue(
"x-original-content-length");
bool via_data_reduction_proxy =
request->response_info().headers->HasHeaderValue(
"via", "1.1 Chrome Compression Proxy");
int64 adjusted_original_content_length = original_content_length;
if (adjusted_original_content_length == -1)
adjusted_original_content_length = received_content_length;
base::TimeDelta freshness_lifetime =
request->response_info().headers->GetFreshnessLifetime(
request->response_info().response_time);
AccumulateContentLength(received_content_length,
adjusted_original_content_length,
via_data_reduction_proxy);
RecordContentLengthHistograms(received_content_length,
original_content_length,
freshness_lifetime);
DVLOG(2) << __FUNCTION__
<< " received content length: " << received_content_length
<< " original content length: " << original_content_length
<< " url: " << request->url();
}
bool is_redirect = request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code());
if (!is_redirect) {
ExtensionWebRequestEventRouter::GetInstance()->OnCompleted(
profile_, extension_info_map_.get(), request);
}
} else if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred(
profile_, extension_info_map_.get(), request, started);
} else {
NOTREACHED();
}
ForwardProxyErrors(request, event_router_.get(), profile_);
ForwardRequestStatus(REQUEST_DONE, request, profile_);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
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 em_ret_near_imm(struct x86_emulate_ctxt *ctxt)
{
int rc;
ctxt->dst.type = OP_REG;
ctxt->dst.addr.reg = &ctxt->_eip;
ctxt->dst.bytes = ctxt->op_bytes;
rc = emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rsp_increment(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int caif_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
int err, size;
struct sk_buff *skb;
int sent = 0;
long timeo;
err = -EOPNOTSUPP;
if (unlikely(msg->msg_flags&MSG_OOB))
goto out_err;
if (unlikely(msg->msg_namelen))
goto out_err;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err);
if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
goto pipe_err;
while (sent < len) {
size = len-sent;
if (size > cf_sk->maxframe)
size = cf_sk->maxframe;
/* If size is more than half of sndbuf, chop up message */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
skb = sock_alloc_send_skb(sk,
size + cf_sk->headroom +
cf_sk->tailroom,
msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
skb_reserve(skb, cf_sk->headroom);
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
err = transmit_skb(skb, cf_sk,
msg->msg_flags&MSG_DONTWAIT, timeo);
if (err < 0)
/* skb is already freed */
goto pipe_err;
sent += size;
}
return sent;
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
return sent ? : err;
}
Commit Message: caif: Fix missing msg_namelen update in caif_seqpkt_recvmsg()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about caif_seqpkt_recvmsg() not filling the msg_name in case it was
set.
Cc: Sjur Braendeland <[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: void QuotaManagerProxy::RegisterClient(QuotaClient* client) {
if (!io_thread_->BelongsToCurrentThread() &&
io_thread_->PostTask(
FROM_HERE,
base::Bind(&QuotaManagerProxy::RegisterClient, this, client))) {
return;
}
if (manager_)
manager_->RegisterClient(client);
else
client->OnQuotaManagerDestroyed();
}
Commit Message: Wipe out QuotaThreadTask.
This is a one of a series of refactoring patches for QuotaManager.
http://codereview.chromium.org/10872054/
http://codereview.chromium.org/10917060/
BUG=139270
Review URL: https://chromiumcodereview.appspot.com/10919070
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 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: float SVGLayoutSupport::calculateScreenFontSizeScalingFactor(const LayoutObject* layoutObject)
{
ASSERT(layoutObject);
AffineTransform ctm = deprecatedCalculateTransformToLayer(layoutObject) * SubtreeContentTransformScope::currentContentTransformation();
ctm.scale(layoutObject->document().frameHost()->deviceScaleFactorDeprecated());
return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID:
Target: 1
Example 2:
Code: void WallpaperManager::SetPolicyControlledWallpaper(
const AccountId& account_id,
std::unique_ptr<user_manager::UserImage> user_image) {
if (!CanGetFilesId()) {
CallWhenCanGetFilesId(
base::Bind(&WallpaperManager::SetPolicyControlledWallpaper,
weak_factory_.GetWeakPtr(), account_id,
base::Passed(std::move(user_image))));
return;
}
const wallpaper::WallpaperFilesId wallpaper_files_id = GetFilesId(account_id);
if (!wallpaper_files_id.is_valid())
LOG(FATAL) << "Wallpaper flies id if invalid!";
SetCustomWallpaper(account_id, wallpaper_files_id, "policy-controlled.jpeg",
wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED,
wallpaper::POLICY, user_image->image(),
user_manager::UserManager::Get()
->IsUserLoggedIn() /* update wallpaper */);
}
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: int do_mathemu(struct pt_regs *regs, struct task_struct *fpt)
{
/* regs->pc isn't necessarily the PC at which the offending insn is sitting.
* The FPU maintains a queue of FPops which cause traps.
* When it hits an instruction that requires that the trapped op succeeded
* (usually because it reads a reg. that the trapped op wrote) then it
* causes this exception. We need to emulate all the insns on the queue
* and then allow the op to proceed.
* This code should also handle the case where the trap was precise,
* in which case the queue length is zero and regs->pc points at the
* single FPop to be emulated. (this case is untested, though :->)
* You'll need this case if you want to be able to emulate all FPops
* because the FPU either doesn't exist or has been software-disabled.
* [The UltraSPARC makes FP a precise trap; this isn't as stupid as it
* might sound because the Ultra does funky things with a superscalar
* architecture.]
*/
/* You wouldn't believe how often I typed 'ftp' when I meant 'fpt' :-> */
int i;
int retcode = 0; /* assume all succeed */
unsigned long insn;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
#ifdef DEBUG_MATHEMU
printk("In do_mathemu()... pc is %08lx\n", regs->pc);
printk("fpqdepth is %ld\n", fpt->thread.fpqdepth);
for (i = 0; i < fpt->thread.fpqdepth; i++)
printk("%d: %08lx at %08lx\n", i, fpt->thread.fpqueue[i].insn,
(unsigned long)fpt->thread.fpqueue[i].insn_addr);
#endif
if (fpt->thread.fpqdepth == 0) { /* no queue, guilty insn is at regs->pc */
#ifdef DEBUG_MATHEMU
printk("precise trap at %08lx\n", regs->pc);
#endif
if (!get_user(insn, (u32 __user *) regs->pc)) {
retcode = do_one_mathemu(insn, &fpt->thread.fsr, fpt->thread.float_regs);
if (retcode) {
/* in this case we need to fix up PC & nPC */
regs->pc = regs->npc;
regs->npc += 4;
}
}
return retcode;
}
/* Normal case: need to empty the queue... */
for (i = 0; i < fpt->thread.fpqdepth; i++) {
retcode = do_one_mathemu(fpt->thread.fpqueue[i].insn, &(fpt->thread.fsr), fpt->thread.float_regs);
if (!retcode) /* insn failed, no point doing any more */
break;
}
/* Now empty the queue and clear the queue_not_empty flag */
if (retcode)
fpt->thread.fsr &= ~(0x3000 | FSR_CEXC_MASK);
else
fpt->thread.fsr &= ~0x3000;
fpt->thread.fpqdepth = 0;
return retcode;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXARIAGridCell::isAriaColumnHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringCase(role, "columnheader");
}
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: static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
aesni_cbc_encrypt(in, out, len, &EVP_C_DATA(EVP_AES_KEY,ctx)->ks.ks,
EVP_CIPHER_CTX_iv_noconst(ctx),
EVP_CIPHER_CTX_encrypting(ctx));
return 1;
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool XmlReader::Load(const std::string& input) {
const int kParseOptions = XML_PARSE_RECOVER | // recover on errors
XML_PARSE_NONET | // forbid network access
XML_PARSE_NOXXE; // no external entities
reader_ = xmlReaderForMemory(input.data(), static_cast<int>(input.size()),
NULL, NULL, kParseOptions);
return reader_ != NULL;
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int cma_connect_ib(struct rdma_id_private *id_priv,
struct rdma_conn_param *conn_param)
{
struct ib_cm_req_param req;
struct rdma_route *route;
void *private_data;
struct ib_cm_id *id;
int offset, ret;
memset(&req, 0, sizeof req);
offset = cma_user_data_offset(id_priv);
req.private_data_len = offset + conn_param->private_data_len;
if (req.private_data_len < conn_param->private_data_len)
return -EINVAL;
if (req.private_data_len) {
private_data = kzalloc(req.private_data_len, GFP_ATOMIC);
if (!private_data)
return -ENOMEM;
} else {
private_data = NULL;
}
if (conn_param->private_data && conn_param->private_data_len)
memcpy(private_data + offset, conn_param->private_data,
conn_param->private_data_len);
id = ib_create_cm_id(id_priv->id.device, cma_ib_handler, id_priv);
if (IS_ERR(id)) {
ret = PTR_ERR(id);
goto out;
}
id_priv->cm_id.ib = id;
route = &id_priv->id.route;
if (private_data) {
ret = cma_format_hdr(private_data, id_priv);
if (ret)
goto out;
req.private_data = private_data;
}
req.primary_path = &route->path_rec[0];
if (route->num_paths == 2)
req.alternate_path = &route->path_rec[1];
req.service_id = rdma_get_service_id(&id_priv->id, cma_dst_addr(id_priv));
req.qp_num = id_priv->qp_num;
req.qp_type = id_priv->id.qp_type;
req.starting_psn = id_priv->seq_num;
req.responder_resources = conn_param->responder_resources;
req.initiator_depth = conn_param->initiator_depth;
req.flow_control = conn_param->flow_control;
req.retry_count = min_t(u8, 7, conn_param->retry_count);
req.rnr_retry_count = min_t(u8, 7, conn_param->rnr_retry_count);
req.remote_cm_response_timeout = CMA_CM_RESPONSE_TIMEOUT;
req.local_cm_response_timeout = CMA_CM_RESPONSE_TIMEOUT;
req.max_cm_retries = CMA_MAX_CM_RETRIES;
req.srq = id_priv->srq ? 1 : 0;
ret = ib_send_cm_req(id_priv->cm_id.ib, &req);
out:
if (ret && !IS_ERR(id)) {
ib_destroy_cm_id(id);
id_priv->cm_id.ib = NULL;
}
kfree(private_data);
return ret;
}
Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler
The code that resolves the passive side source MAC within the rdma_cm
connection request handler was both redundant and buggy, so remove it.
It was redundant since later, when an RC QP is modified to RTR state,
the resolution will take place in the ib_core module. It was buggy
because this callback also deals with UD SIDR exchange, for which we
incorrectly looked at the REQ member of the CM event and dereferenced
a random value.
Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures")
Signed-off-by: Moni Shoua <[email protected]>
Signed-off-by: Or Gerlitz <[email protected]>
Signed-off-by: Roland Dreier <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 WebBluetoothServiceImpl::ClearState() {
characteristic_id_to_notify_session_.clear();
pending_primary_services_requests_.clear();
descriptor_id_to_characteristic_id_.clear();
characteristic_id_to_service_id_.clear();
service_id_to_device_address_.clear();
connected_devices_.reset(
new FrameConnectedBluetoothDevices(render_frame_host_));
device_chooser_controller_.reset();
BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this);
}
Commit Message: Ensure device choosers are closed on navigation
The requestDevice() IPCs can race with navigation. This change ensures
that choosers are closed on navigation and adds browser tests to
exercise this for Web Bluetooth and WebUSB.
Bug: 723503
Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c
Reviewed-on: https://chromium-review.googlesource.com/1099961
Commit-Queue: Reilly Grant <[email protected]>
Reviewed-by: Michael Wasserman <[email protected]>
Reviewed-by: Jeffrey Yasskin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#569900}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int inotify_release(struct inode *ignored, struct file *file)
{
struct fsnotify_group *group = file->private_data;
struct user_struct *user = group->inotify_data.user;
pr_debug("%s: group=%p\n", __func__, group);
fsnotify_clear_marks_by_group(group);
/* free this group, matching get was inotify_init->fsnotify_obtain_group */
fsnotify_put_group(group);
atomic_dec(&user->inotify_devs);
return 0;
}
Commit Message: inotify: fix double free/corruption of stuct user
On an error path in inotify_init1 a normal user can trigger a double
free of struct user. This is a regression introduced by a2ae4cc9a16e
("inotify: stop kernel memory leak on file creation failure").
We fix this by making sure that if a group exists the user reference is
dropped when the group is cleaned up. We should not explictly drop the
reference on error and also drop the reference when the group is cleaned
up.
The new lifetime rules are that an inotify group lives from
inotify_new_group to the last fsnotify_put_group. Since the struct user
and inotify_devs are directly tied to this lifetime they are only
changed/updated in those two locations. We get rid of all special
casing of struct user or user->inotify_devs.
Signed-off-by: Eric Paris <[email protected]>
Cc: [email protected] (2.6.37 and up)
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool TabCloseableStateWatcher::CanCloseTab(const Browser* browser) const {
return browser->type() != Browser::TYPE_NORMAL ? true :
(can_close_tab_ || waiting_for_browser_);
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rawv6_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ: {
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ: {
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL)
amount = skb_tail_pointer(skb) -
skb_transport_header(skb);
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
default:
#ifdef CONFIG_IPV6_MROUTE
return ip6mr_ioctl(sk, cmd, (void __user *)arg);
#else
return -ENOIOCTLCMD;
#endif
}
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[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-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 bool ldb_dn_explode(struct ldb_dn *dn)
{
char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t;
bool trim = true;
bool in_extended = true;
bool in_ex_name = false;
bool in_ex_value = false;
bool in_attr = false;
bool in_value = false;
bool in_quote = false;
bool is_oid = false;
bool escape = false;
unsigned int x;
size_t l = 0;
int ret;
char *parse_dn;
bool is_index;
if ( ! dn || dn->invalid) return false;
if (dn->components) {
return true;
}
if (dn->ext_linearized) {
parse_dn = dn->ext_linearized;
} else {
parse_dn = dn->linearized;
}
if ( ! parse_dn ) {
return false;
}
is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0);
/* Empty DNs */
if (parse_dn[0] == '\0') {
return true;
}
/* Special DNs case */
if (dn->special) {
return true;
}
/* make sure we free this if allocated previously before replacing */
LDB_FREE(dn->components);
dn->comp_num = 0;
LDB_FREE(dn->ext_components);
dn->ext_comp_num = 0;
/* in the common case we have 3 or more components */
/* make sure all components are zeroed, other functions depend on it */
dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3);
if ( ! dn->components) {
return false;
}
/* Components data space is allocated here once */
data = talloc_array(dn->components, char, strlen(parse_dn) + 1);
if (!data) {
return false;
}
p = parse_dn;
t = NULL;
d = dt = data;
while (*p) {
if (in_extended) {
if (!in_ex_name && !in_ex_value) {
if (p[0] == '<') {
p++;
ex_name = d;
in_ex_name = true;
continue;
} else if (p[0] == '\0') {
p++;
continue;
} else {
in_extended = false;
in_attr = true;
dt = d;
continue;
}
}
if (in_ex_name && *p == '=') {
*d++ = '\0';
p++;
ex_value = d;
in_ex_name = false;
in_ex_value = true;
continue;
}
if (in_ex_value && *p == '>') {
const struct ldb_dn_extended_syntax *ext_syntax;
struct ldb_val ex_val = {
.data = (uint8_t *)ex_value,
.length = d - ex_value
};
*d++ = '\0';
p++;
in_ex_value = false;
/* Process name and ex_value */
dn->ext_components = talloc_realloc(dn,
dn->ext_components,
struct ldb_dn_ext_component,
dn->ext_comp_num + 1);
if ( ! dn->ext_components) {
/* ouch ! */
goto failed;
}
ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name);
if (!ext_syntax) {
/* We don't know about this type of extended DN */
goto failed;
}
dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name);
if (!dn->ext_components[dn->ext_comp_num].name) {
/* ouch */
goto failed;
}
ret = ext_syntax->read_fn(dn->ldb, dn->ext_components,
&ex_val, &dn->ext_components[dn->ext_comp_num].value);
if (ret != LDB_SUCCESS) {
ldb_dn_mark_invalid(dn);
goto failed;
}
dn->ext_comp_num++;
if (*p == '\0') {
/* We have reached the end (extended component only)! */
talloc_free(data);
return true;
} else if (*p == ';') {
p++;
continue;
} else {
ldb_dn_mark_invalid(dn);
goto failed;
}
}
*d++ = *p++;
continue;
}
if (in_attr) {
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (isdigit(*p)) {
is_oid = true;
} else
if ( ! isalpha(*p)) {
/* not a digit nor an alpha,
* invalid attribute name */
ldb_dn_mark_invalid(dn);
goto failed;
}
/* Copy this character across from parse_dn,
* now we have trimmed out spaces */
*d++ = *p++;
continue;
}
if (*p == ' ') {
p++;
/* valid only if we are at the end */
trim = true;
continue;
}
if (trim && (*p != '=')) {
/* spaces/tabs are not allowed */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (*p == '=') {
/* attribute terminated */
in_attr = false;
in_value = true;
trim = true;
l = 0;
/* Terminate this string in d
* (which is a copy of parse_dn
* with spaces trimmed) */
*d++ = '\0';
dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt);
if ( ! dn->components[dn->comp_num].name) {
/* ouch */
goto failed;
}
dt = d;
p++;
continue;
}
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) {
/* not a digit nor a dot,
* invalid attribute oid */
ldb_dn_mark_invalid(dn);
goto failed;
} else
if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) {
/* not ALPHA, DIGIT or HYPHEN */
ldb_dn_mark_invalid(dn);
goto failed;
}
*d++ = *p++;
continue;
}
if (in_value) {
if (in_quote) {
if (*p == '\"') {
if (p[-1] != '\\') {
p++;
in_quote = false;
continue;
}
}
*d++ = *p++;
l++;
continue;
}
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (*p == '\"') {
in_quote = true;
p++;
continue;
}
}
switch (*p) {
/* TODO: support ber encoded values
case '#':
*/
case ',':
if (escape) {
*d++ = *p++;
l++;
escape = false;
continue;
}
/* ok found value terminator */
if ( t ) {
/* trim back */
d -= (p - t);
l -= (p - t);
}
in_attr = true;
in_value = false;
trim = true;
p++;
*d++ = '\0';
dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt);
dn->components[dn->comp_num].value.length = l;
if ( ! dn->components[dn->comp_num].value.data) {
/* ouch ! */
goto failed;
}
dt = d;
dn->components,
struct ldb_dn_component,
dn->comp_num + 1);
if ( ! dn->components) {
/* ouch ! */
goto failed;
}
/* make sure all components are zeroed, other functions depend on this */
memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component));
}
continue;
case '+':
case '=':
/* to main compatibility with earlier
versions of ldb indexing, we have to
accept the base64 encoded binary index
values, which contain a '+' or '='
which should normally be escaped */
if (is_index) {
if ( t ) t = NULL;
*d++ = *p++;
l++;
break;
}
/* fall through */
case '\"':
case '<':
case '>':
case ';':
/* a string with not escaped specials is invalid (tested) */
if ( ! escape) {
ldb_dn_mark_invalid(dn);
goto failed;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
case '\\':
if ( ! escape) {
escape = true;
p++;
continue;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
default:
if (escape) {
if (isxdigit(p[0]) && isxdigit(p[1])) {
if (sscanf(p, "%02x", &x) != 1) {
/* invalid escaping sequence */
ldb_dn_mark_invalid(dn);
goto failed;
}
p += 2;
*d++ = (unsigned char)x;
} else {
*d++ = *p++;
}
escape = false;
l++;
if ( t ) t = NULL;
break;
}
if (*p == ' ') {
if ( ! t) t = p;
} else {
if ( t ) t = NULL;
}
*d++ = *p++;
l++;
break;
}
}
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: std::string SessionManager::GetAddress() {
std::string hostname = net::GetHostName();
#if defined(OS_WIN)
if (hostname.length()) {
struct hostent* host_entry = gethostbyname(hostname.c_str());
if (host_entry)
hostname = host_entry->h_name;
}
#endif
if (hostname.empty()) {
hostname = "localhost";
}
return hostname + ":" + port_ + url_base_;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void p4_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
int thread = p4_ht_config_thread(hwc->config);
u64 escr_conf = p4_config_unpack_escr(p4_clear_ht_bit(hwc->config));
unsigned int idx = p4_config_unpack_event(hwc->config);
struct p4_event_bind *bind;
u64 escr_addr, cccr;
bind = &p4_event_bind_map[idx];
escr_addr = (u64)bind->escr_msr[thread];
/*
* - we dont support cascaded counters yet
* - and counter 1 is broken (erratum)
*/
WARN_ON_ONCE(p4_is_event_cascaded(hwc->config));
WARN_ON_ONCE(hwc->idx == 1);
/* we need a real Event value */
escr_conf &= ~P4_ESCR_EVENT_MASK;
escr_conf |= P4_ESCR_EVENT(P4_OPCODE_EVNT(bind->opcode));
cccr = p4_config_unpack_cccr(hwc->config);
/*
* it could be Cache event so we need to write metrics
* into additional MSRs
*/
p4_pmu_enable_pebs(hwc->config);
(void)checking_wrmsrl(escr_addr, escr_conf);
(void)checking_wrmsrl(hwc->config_base,
(cccr & ~P4_CCCR_RESERVED) | P4_CCCR_ENABLE);
}
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: userauth_hostbased(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *cuser, *chost;
u_char *pkblob, *sig;
size_t alen, blen, slen;
int r, pktype, authenticated = 0;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
/* XXX use sshkey_froms() */
if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
(r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
(r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
fatal("%s: packet parsing: %s", __func__, ssh_err(r));
debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
debug("signature:");
sshbuf_dump_data(sig, siglen, stderr);
#endif
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
logit("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: key_from_blob: %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) {
error("Refusing RSA key because peer uses unsafe "
"signature format");
goto done;
}
if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
__func__, sshkey_type(key));
goto done;
}
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
/* reconstruct packet */
if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
(r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
(r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
(r = sshbuf_put_cstring(b, chost)) != 0 ||
(r = sshbuf_put_cstring(b, cuser)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
auth2_record_info(authctxt,
"client user \"%.100s\", client host \"%.100s\"", cuser, chost);
/* test for allowed key and correct signature */
authenticated = 0;
if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
authenticated = 1;
auth2_record_key(authctxt, authenticated, key);
sshbuf_free(b);
done:
debug2("%s: authenticated %d", __func__, authenticated);
sshkey_free(key);
free(pkalg);
free(pkblob);
free(cuser);
free(chost);
free(sig);
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
Target: 1
Example 2:
Code: static void perWorldBindingsLongAttributeAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
ExceptionState exceptionState(ExceptionState::SetterContext, "perWorldBindingsLongAttribute", "TestObjectPython", info.Holder(), info.GetIsolate());
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_EXCEPTION_VOID(int, cppValue, toInt32(jsValue, exceptionState), exceptionState);
imp->setPerWorldBindingsLongAttribute(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: int ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
base::CommandLine* singleton_command_line =
base::CommandLine::ForCurrentProcess();
if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitch(::switches::kDisableSync);
singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
browser_defaults::bookmarks_enabled = false;
}
if (!base::SysInfo::IsRunningOnChromeOS() &&
!parsed_command_line().HasSwitch(switches::kLoginManager) &&
!parsed_command_line().HasSwitch(switches::kLoginUser) &&
!parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitchASCII(
switches::kLoginUser,
cryptohome::Identification(user_manager::StubAccountId()).id());
if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
chrome::kTestUserProfileDir);
}
LOG(WARNING) << "Running as stub user with profile dir: "
<< singleton_command_line
->GetSwitchValuePath(switches::kLoginProfile)
.value();
}
RegisterStubPathOverridesIfNecessary();
#if defined(GOOGLE_CHROME_BUILD)
const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
std::string channel;
if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
chrome::SetChannel(channel);
#endif
dbus_pre_early_init_ = std::make_unique<internal::DBusPreEarlyInit>();
return ChromeBrowserMainPartsLinux::PreEarlyInitialization();
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <[email protected]>
Commit-Queue: Sam McNally <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567513}
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 void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
list_add_tail(&io_end->list,
&EXT4_I(io_end->inode)->i_completed_io_list);
iocb->private = NULL;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: struct file *dentry_open(const struct path *path, int flags,
const struct cred *cred)
{
int error;
struct file *f;
validate_creds(cred);
/* We must always pass in a valid mount pointer. */
BUG_ON(!path->mnt);
f = get_empty_filp();
if (!IS_ERR(f)) {
f->f_flags = flags;
f->f_path = *path;
error = do_dentry_open(f, NULL, cred);
if (!error) {
/* from now on we need fput() to dispose of f */
error = open_check_o_direct(f);
if (error) {
fput(f);
f = ERR_PTR(error);
}
} else {
put_filp(f);
f = ERR_PTR(error);
}
}
return f;
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void runTest()
{
webkit_support::PostDelayedTask(CCLayerTreeHostTest::onBeginTest, static_cast<void*>(this), 0);
webkit_support::PostDelayedTask(CCLayerTreeHostTest::testTimeout, static_cast<void*>(this), 5000);
webkit_support::RunMessageLoop();
m_running = false;
bool timedOut = m_timedOut; // Save whether we're timed out in case RunAllPendingMessages has the timeout.
webkit_support::RunAllPendingMessages();
ASSERT(!m_layerTreeHost.get());
m_client.clear();
if (timedOut) {
FAIL() << "Test timed out";
return;
}
afterTest();
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
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 GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT("
<< GLES2Util::GetStringQueryTarget(target) << ", " << id
<< ")");
switch (target) {
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_COMPLETED_CHROMIUM:
if (!capabilities_.sync_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for commands completed queries");
return;
}
break;
case GL_SAMPLES_PASSED_ARB:
if (!capabilities_.occlusion_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for occlusion queries");
return;
}
break;
case GL_ANY_SAMPLES_PASSED:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
if (!capabilities_.occlusion_query_boolean) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for boolean occlusion queries");
return;
}
break;
case GL_TIME_ELAPSED_EXT:
if (!capabilities_.timer_queries) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for timing queries");
return;
}
break;
case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
if (capabilities_.major_version >= 3)
break;
FALLTHROUGH;
default:
SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target");
return;
}
if (query_tracker_->GetCurrentQuery(target)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"query already in progress");
return;
}
if (id == 0) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0");
return;
}
if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id");
return;
}
switch (target) {
case GL_TIME_ELAPSED_EXT:
if (!query_tracker_->SetDisjointSync(this)) {
SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT",
"buffer allocation failed");
return;
}
break;
default:
break;
}
if (query_tracker_->BeginQuery(id, target, this))
CheckGLError();
if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) {
AllocateShadowCopiesForReadback();
}
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int hfsplus_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int res;
/* Unlink destination if it already exists */
if (new_dentry->d_inode) {
if (S_ISDIR(new_dentry->d_inode->i_mode))
res = hfsplus_rmdir(new_dir, new_dentry);
else
res = hfsplus_unlink(new_dir, new_dentry);
if (res)
return res;
}
res = hfsplus_rename_cat((u32)(unsigned long)old_dentry->d_fsdata,
old_dir, &old_dentry->d_name,
new_dir, &new_dentry->d_name);
if (!res)
new_dentry->d_fsdata = old_dentry->d_fsdata;
return res;
}
Commit Message: hfsplus: Fix potential buffer overflows
Commit ec81aecb2966 ("hfs: fix a potential buffer overflow") fixed a few
potential buffer overflows in the hfs filesystem. But as Timo Warns
pointed out, these changes also need to be made on the hfsplus
filesystem as well.
Reported-by: Timo Warns <[email protected]>
Acked-by: WANG Cong <[email protected]>
Cc: Alexey Khoroshilov <[email protected]>
Cc: Miklos Szeredi <[email protected]>
Cc: Sage Weil <[email protected]>
Cc: Eugene Teo <[email protected]>
Cc: Roman Zippel <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Christoph Hellwig <[email protected]>
Cc: Alexey Dobriyan <[email protected]>
Cc: Dave Anderson <[email protected]>
Cc: stable <[email protected]>
Cc: Andrew Morton <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: setup_arch (char **cmdline_p)
{
unw_init();
ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);
*cmdline_p = __va(ia64_boot_param->command_line);
strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);
efi_init();
io_port_init();
#ifdef CONFIG_IA64_GENERIC
/* machvec needs to be parsed from the command line
* before parse_early_param() is called to ensure
* that ia64_mv is initialised before any command line
* settings may cause console setup to occur
*/
machvec_init_from_cmdline(*cmdline_p);
#endif
parse_early_param();
if (early_console_setup(*cmdline_p) == 0)
mark_bsp_online();
#ifdef CONFIG_ACPI
/* Initialize the ACPI boot-time table parser */
acpi_table_init();
# ifdef CONFIG_ACPI_NUMA
acpi_numa_init();
per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?
32 : cpus_weight(early_cpu_possible_map)), additional_cpus);
# endif
#else
# ifdef CONFIG_SMP
smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */
# endif
#endif /* CONFIG_APCI_BOOT */
find_memory();
/* process SAL system table: */
ia64_sal_init(__va(efi.sal_systab));
#ifdef CONFIG_SMP
cpu_physical_id(0) = hard_smp_processor_id();
#endif
cpu_init(); /* initialize the bootstrap CPU */
mmu_context_init(); /* initialize context_id bitmap */
check_sal_cache_flush();
#ifdef CONFIG_ACPI
acpi_boot_init();
#endif
#ifdef CONFIG_VT
if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
/*
* Non-legacy systems may route legacy VGA MMIO range to system
* memory. vga_con probes the MMIO hole, so memory looks like
* a VGA device to it. The EFI memory map can tell us if it's
* memory so we can avoid this problem.
*/
if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
conswitchp = &vga_con;
# endif
}
#endif
/* enable IA-64 Machine Check Abort Handling unless disabled */
if (!nomca)
ia64_mca_init();
platform_setup(cmdline_p);
paging_init();
}
Commit Message: [IA64] Workaround for RSE issue
Problem: An application violating the architectural rules regarding
operation dependencies and having specific Register Stack Engine (RSE)
state at the time of the violation, may result in an illegal operation
fault and invalid RSE state. Such faults may initiate a cascade of
repeated illegal operation faults within OS interruption handlers.
The specific behavior is OS dependent.
Implication: An application causing an illegal operation fault with
specific RSE state may result in a series of illegal operation faults
and an eventual OS stack overflow condition.
Workaround: OS interruption handlers that switch to kernel backing
store implement a check for invalid RSE state to avoid the series
of illegal operation faults.
The core of the workaround is the RSE_WORKAROUND code sequence
inserted into each invocation of the SAVE_MIN_WITH_COVER and
SAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded
constants that depend on the number of stacked physical registers
being 96. The rest of this patch consists of code to disable this
workaround should this not be the case (with the presumption that
if a future Itanium processor increases the number of registers, it
would also remove the need for this patch).
Move the start of the RBS up to a mod32 boundary to avoid some
corner cases.
The dispatch_illegal_op_fault code outgrew the spot it was
squatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y
Move it out to the end of the ivt.
Signed-off-by: Tony Luck <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
{
assert(pTrack);
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j)
{
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; //no matching track number found
}
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: bool ProfileSyncService::HasUnsyncedItems() const {
if (backend_.get() && backend_initialized_) {
return backend_->HasUnsyncedItems();
}
NOTREACHED();
return false;
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: DictionaryValue* GetNetworkInfoDict(const chromeos::Network* network) {
DictionaryValue* item = new DictionaryValue;
item->SetString("name", network->name());
item->SetString("device_path", network->device_path());
item->SetString("ip_address", network->ip_address());
item->SetString("status", network->GetStateString());
return item;
}
Commit Message: chromeos: Move audio, power, and UI files into subdirs.
This moves more files from chrome/browser/chromeos/ into
subdirectories.
BUG=chromium-os:22896
TEST=did chrome os builds both with and without aura
TBR=sky
Review URL: http://codereview.chromium.org/9125006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 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: long Cluster::GetIndex() const
{
return m_index;
}
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: GF_Box *clap_New()
{
ISOM_DECL_BOX_ALLOC(GF_CleanApertureBox, GF_ISOM_BOX_TYPE_CLAP);
return (GF_Box *)tmp;
}
Commit Message: prevent dref memleak on invalid input (#1183)
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: set_string_2_svc(sstring_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_mod_strings", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_set_string((void *)handle, arg->princ, arg->key,
arg->value);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_mod_strings", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
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: TestWCDelegateForDialogsAndFullscreen()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Target: 1
Example 2:
Code: static void cachedDirtyableAttributeRaisesAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::cachedDirtyableAttributeRaisesAttributeGetter(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 TriggerReloadPromptOnClose() const {
PageInfoBubbleView* const page_info_bubble_view =
static_cast<PageInfoBubbleView*>(
PageInfoBubbleView::GetPageInfoBubble());
ASSERT_NE(nullptr, page_info_bubble_view);
PageInfoUI::PermissionInfo permission;
permission.type = ContentSettingsType::CONTENT_SETTINGS_TYPE_NOTIFICATIONS;
permission.setting = ContentSetting::CONTENT_SETTING_BLOCK;
permission.default_setting = ContentSetting::CONTENT_SETTING_ASK;
permission.source = content_settings::SettingSource::SETTING_SOURCE_USER;
permission.is_incognito = false;
page_info_bubble_view->OnPermissionChanged(permission);
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311
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 IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterStringPref(prefs::kAuthSchemes,
"basic,digest,ntlm,negotiate,"
"spdyproxy");
registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
std::string());
registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
registry->RegisterStringPref(prefs::kSpdyProxyAuthOrigin, std::string());
registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0);
registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0);
#if defined(OS_ANDROID) || defined(OS_IOS)
registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength);
registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength);
registry->RegisterListPref(
prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled);
registry->RegisterListPref(
prefs::kDailyContentLengthWithDataReductionProxyEnabled);
registry->RegisterListPref(
prefs::kDailyOriginalContentLengthViaDataReductionProxy);
registry->RegisterListPref(
prefs::kDailyContentLengthViaDataReductionProxy);
registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, 0L);
#endif
registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Target: 1
Example 2:
Code: void UserActivityDetector::AddObserver(UserActivityObserver* observer) {
observers_.AddObserver(observer);
}
Commit Message: ash: Make UserActivityDetector ignore synthetic mouse events
This may have been preventing us from suspending (e.g.
mouse event is synthesized in response to lock window being
shown so Chrome tells powerd that the user is active).
BUG=133419
TEST=added
Review URL: https://chromiumcodereview.appspot.com/10574044
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143437 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void write_pack_file(void)
{
uint32_t i = 0, j;
struct sha1file *f;
off_t offset;
uint32_t nr_remaining = nr_result;
time_t last_mtime = 0;
struct object_entry **write_order;
if (progress > pack_to_stdout)
progress_state = start_progress(_("Writing objects"), nr_result);
written_list = xmalloc(to_pack.nr_objects * sizeof(*written_list));
write_order = compute_write_order();
do {
unsigned char sha1[20];
char *pack_tmp_name = NULL;
if (pack_to_stdout)
f = sha1fd_throughput(1, "<stdout>", progress_state);
else
f = create_tmp_packfile(&pack_tmp_name);
offset = write_pack_header(f, nr_remaining);
if (reuse_packfile) {
off_t packfile_size;
assert(pack_to_stdout);
packfile_size = write_reused_pack(f);
offset += packfile_size;
}
nr_written = 0;
for (; i < to_pack.nr_objects; i++) {
struct object_entry *e = write_order[i];
if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
break;
display_progress(progress_state, written);
}
/*
* Did we write the wrong # entries in the header?
* If so, rewrite it like in fast-import
*/
if (pack_to_stdout) {
sha1close(f, sha1, CSUM_CLOSE);
} else if (nr_written == nr_remaining) {
sha1close(f, sha1, CSUM_FSYNC);
} else {
int fd = sha1close(f, sha1, 0);
fixup_pack_header_footer(fd, sha1, pack_tmp_name,
nr_written, sha1, offset);
close(fd);
write_bitmap_index = 0;
}
if (!pack_to_stdout) {
struct stat st;
struct strbuf tmpname = STRBUF_INIT;
/*
* Packs are runtime accessed in their mtime
* order since newer packs are more likely to contain
* younger objects. So if we are creating multiple
* packs then we should modify the mtime of later ones
* to preserve this property.
*/
if (stat(pack_tmp_name, &st) < 0) {
warning("failed to stat %s: %s",
pack_tmp_name, strerror(errno));
} else if (!last_mtime) {
last_mtime = st.st_mtime;
} else {
struct utimbuf utb;
utb.actime = st.st_atime;
utb.modtime = --last_mtime;
if (utime(pack_tmp_name, &utb) < 0)
warning("failed utime() on %s: %s",
pack_tmp_name, strerror(errno));
}
strbuf_addf(&tmpname, "%s-", base_name);
if (write_bitmap_index) {
bitmap_writer_set_checksum(sha1);
bitmap_writer_build_type_index(written_list, nr_written);
}
finish_tmp_packfile(&tmpname, pack_tmp_name,
written_list, nr_written,
&pack_idx_opts, sha1);
if (write_bitmap_index) {
strbuf_addf(&tmpname, "%s.bitmap", sha1_to_hex(sha1));
stop_progress(&progress_state);
bitmap_writer_show_progress(progress);
bitmap_writer_reuse_bitmaps(&to_pack);
bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
bitmap_writer_build(&to_pack);
bitmap_writer_finish(written_list, nr_written,
tmpname.buf, write_bitmap_options);
write_bitmap_index = 0;
}
strbuf_release(&tmpname);
free(pack_tmp_name);
puts(sha1_to_hex(sha1));
}
/* mark written objects as written to previous pack */
for (j = 0; j < nr_written; j++) {
written_list[j]->offset = (off_t)-1;
}
nr_remaining -= nr_written;
} while (nr_remaining && i < to_pack.nr_objects);
free(written_list);
free(write_order);
stop_progress(&progress_state);
if (written != nr_result)
die("wrote %"PRIu32" objects while expecting %"PRIu32,
written, nr_result);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext4_mb_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
Target: 1
Example 2:
Code: static int reinstate_path(struct pgpath *pgpath)
{
int r = 0;
unsigned long flags;
struct multipath *m = pgpath->pg->m;
spin_lock_irqsave(&m->lock, flags);
if (pgpath->is_active)
goto out;
if (!pgpath->pg->ps.type->reinstate_path) {
DMWARN("Reinstate path not supported by path selector %s",
pgpath->pg->ps.type->name);
r = -EINVAL;
goto out;
}
r = pgpath->pg->ps.type->reinstate_path(&pgpath->pg->ps, &pgpath->path);
if (r)
goto out;
pgpath->is_active = 1;
if (!m->nr_valid_paths++ && m->queue_size) {
m->current_pgpath = NULL;
queue_work(kmultipathd, &m->process_queued_ios);
} else if (m->hw_handler_name && (m->current_pg == pgpath->pg)) {
if (queue_work(kmpath_handlerd, &pgpath->activate_path.work))
m->pg_init_in_progress++;
}
dm_path_uevent(DM_UEVENT_PATH_REINSTATED, m->ti,
pgpath->path.dev->name, m->nr_valid_paths);
schedule_work(&m->trigger_event);
out:
spin_unlock_irqrestore(&m->lock, flags);
return r;
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SchedulerObject* SchedulerObject::getInstance()
{
if (!m_instance) {
m_instance = new SchedulerObject();
}
return m_instance;
}
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: void PreconnectManager::Start(const GURL& url,
std::vector<PreconnectRequest> requests) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string host = url.host();
if (preresolve_info_.find(host) != preresolve_info_.end())
return;
auto iterator_and_whether_inserted = preresolve_info_.emplace(
host, std::make_unique<PreresolveInfo>(url, requests.size()));
PreresolveInfo* info = iterator_and_whether_inserted.first->second.get();
for (auto request_it = requests.begin(); request_it != requests.end();
++request_it) {
DCHECK(request_it->origin.GetOrigin() == request_it->origin);
PreresolveJobId job_id = preresolve_jobs_.Add(
std::make_unique<PreresolveJob>(std::move(*request_it), info));
queued_jobs_.push_back(job_id);
}
TryToLaunchPreresolveJobs();
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
Target: 1
Example 2:
Code: Locale& Document::getCachedLocale(const AtomicString& locale)
{
AtomicString localeKey = locale;
if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
return Locale::defaultLocale();
LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
if (result.isNewEntry)
result.storedValue->value = Locale::create(localeKey);
return *(result.storedValue->value);
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
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: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value)
{
/*
* Convert jiffies to nanoseconds and separate with
* one divide.
*/
u64 nsec = (u64)jiffies * TICK_NSEC;
long rem;
value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem);
value->tv_usec = rem / NSEC_PER_USEC;
}
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: | 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: xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *elemName;
const xmlChar *attrName;
xmlEnumerationPtr tree;
if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
xmlParserInputPtr input = ctxt->input;
SKIP(9);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
SKIP_BLANKS;
elemName = xmlParseName(ctxt);
if (elemName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Element\n");
return;
}
SKIP_BLANKS;
GROW;
while (RAW != '>') {
const xmlChar *check = CUR_PTR;
int type;
int def;
xmlChar *defaultValue = NULL;
GROW;
tree = NULL;
attrName = xmlParseName(ctxt);
if (attrName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Attribute\n");
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
SKIP_BLANKS;
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
def = xmlParseDefaultDecl(ctxt, &defaultValue);
if (def <= 0) {
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
xmlAttrNormalizeSpace(defaultValue, defaultValue);
GROW;
if (RAW != '>') {
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute default value\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
}
if (check == CUR_PTR) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"in xmlParseAttributeListDecl\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->attributeDecl != NULL))
ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
type, def, defaultValue, tree);
else if (tree != NULL)
xmlFreeEnumeration(tree);
if ((ctxt->sax2) && (defaultValue != NULL) &&
(def != XML_ATTRIBUTE_IMPLIED) &&
(def != XML_ATTRIBUTE_REQUIRED)) {
xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
}
if (ctxt->sax2) {
xmlAddSpecialAttr(ctxt, elemName, attrName, type);
}
if (defaultValue != NULL)
xmlFree(defaultValue);
GROW;
}
if (RAW == '>') {
if (input != ctxt->input) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
}
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: nfsd4_free_slabs(void)
{
kmem_cache_destroy(odstate_slab);
kmem_cache_destroy(openowner_slab);
kmem_cache_destroy(lockowner_slab);
kmem_cache_destroy(file_slab);
kmem_cache_destroy(stateid_slab);
kmem_cache_destroy(deleg_slab);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static EAS_RESULT Parse_rgn (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_I32 size, EAS_U16 artIndex)
{
EAS_RESULT result;
EAS_U32 temp;
EAS_I32 chunkPos;
EAS_I32 endChunk;
EAS_I32 rgnhPos;
EAS_I32 lartPos;
EAS_I32 lartSize;
EAS_I32 lar2Pos;
EAS_I32 lar2Size;
EAS_I32 wlnkPos;
EAS_I32 wsmpPos;
EAS_U32 waveIndex;
S_DLS_ART_VALUES art;
S_WSMP_DATA wsmp;
S_WSMP_DATA *pWsmp;
EAS_U16 regionIndex;
/* seek to start of chunk */
if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS)
return result;
/* no chunks found yet */
rgnhPos = lartPos = lartSize = lar2Pos = lar2Size = wsmpPos = wlnkPos = 0;
regionIndex = (EAS_U16) pDLSData->regionCount;
/* read to end of chunk */
endChunk = pos + size;
while (pos < endChunk)
{
chunkPos = pos;
/* get the next chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_CDL:
if ((result = Parse_cdl(pDLSData, size, &temp)) != EAS_SUCCESS)
return result;
/* if conditional chunk evaluates false, skip this list */
if (!temp)
return EAS_SUCCESS;
break;
case CHUNK_RGNH:
rgnhPos = chunkPos + 8;
break;
case CHUNK_WLNK:
wlnkPos = chunkPos + 8;
break;
case CHUNK_WSMP:
wsmpPos = chunkPos + 8;
break;
case CHUNK_LART:
lartPos = chunkPos + 12;
lartSize = size;
break;
case CHUNK_LAR2:
lar2Pos = chunkPos + 12;
lar2Size = size;
break;
default:
break;
}
}
/* must have a rgnh chunk to be useful */
if (!rgnhPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS rgn chunk has no rgnh chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a wlnk chunk to be useful */
if (!wlnkPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS rgn chunk has no wlnk chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* parse wlnk chunk */
if ((result = Parse_wlnk(pDLSData, wlnkPos, &waveIndex)) != EAS_SUCCESS)
return result;
if (waveIndex >= pDLSData->waveCount)
{
return EAS_FAILURE;
}
pWsmp = &pDLSData->wsmpData[waveIndex];
/* if there is any articulation data, parse it */
EAS_HWMemCpy(&art, &defaultArt, sizeof(S_DLS_ART_VALUES));
if (lartPos)
{
if ((result = Parse_lart(pDLSData, lartPos, lartSize, &art)) != EAS_SUCCESS)
return result;
}
if (lar2Pos)
{
if ((result = Parse_lart(pDLSData, lar2Pos, lar2Size, &art)) != EAS_SUCCESS)
return result;
}
/* if second pass, process region header */
if (pDLSData->pDLS)
{
/* if local data was found convert it */
if (art.values[PARAM_MODIFIED] == EAS_TRUE)
{
Convert_art(pDLSData, &art, (EAS_U16) pDLSData->artCount);
artIndex = (EAS_U16) pDLSData->artCount;
}
/* parse region header */
if ((result = Parse_rgnh(pDLSData, rgnhPos, &pDLSData->pDLS->pDLSRegions[regionIndex & REGION_INDEX_MASK])) != EAS_SUCCESS)
return result;
/* parse wsmp chunk, copying parameters from original first */
if (wsmpPos)
{
EAS_HWMemCpy(&wsmp, pWsmp, sizeof(wsmp));
if ((result = Parse_wsmp(pDLSData, wsmpPos, &wsmp)) != EAS_SUCCESS)
return result;
pWsmp = &wsmp;
}
Convert_rgn(pDLSData, regionIndex, artIndex, (EAS_U16) waveIndex, pWsmp);
/* ensure loopStart and loopEnd fall in the range */
if (pWsmp->loopLength != 0)
{
EAS_U32 sampleLen = pDLSData->pDLS->pDLSSampleLen[waveIndex];
if (sampleLen < sizeof(EAS_SAMPLE)
|| (pWsmp->loopStart + pWsmp->loopLength) * sizeof(EAS_SAMPLE) > sampleLen - sizeof(EAS_SAMPLE))
{
return EAS_FAILURE;
}
}
}
/* if local articulation, bump count */
if (art.values[PARAM_MODIFIED])
pDLSData->artCount++;
/* increment region count */
pDLSData->regionCount++;
return EAS_SUCCESS;
}
Commit Message: Fix NULL pointer dereference
Bug: 29770686
Bug: 23304983
Change-Id: I1648aab90bc281702a00744bf884ae8bb8009412
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void msleep(uint64_t ms) {
usleep(ms * 1000);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: void ping_proc_unregister(struct net *net, struct ping_seq_afinfo *afinfo)
{
remove_proc_entry(afinfo->name, net->proc_net);
}
Commit Message: ping: prevent NULL pointer dereference on write to msg_name
A plain read() on a socket does set msg->msg_name to NULL. So check for
NULL pointer first.
Signed-off-by: Hannes Frederic Sowa <[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: static void CreateSensorFusion(
mojo::ScopedSharedBufferMapping mapping,
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm,
const PlatformSensorProviderBase::CreateSensorCallback& callback,
PlatformSensorProvider* provider) {
scoped_refptr<Factory> factory(new Factory(std::move(mapping),
std::move(fusion_algorithm),
std::move(callback), provider));
factory->FetchSources();
}
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: static int try_smi_init(struct smi_info *new_smi)
{
int rv = 0;
int i;
char *init_name = NULL;
pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n",
ipmi_addr_src_to_str(new_smi->io.addr_source),
si_to_str[new_smi->io.si_type],
addr_space_to_str[new_smi->io.addr_type],
new_smi->io.addr_data,
new_smi->io.slave_addr, new_smi->io.irq);
switch (new_smi->io.si_type) {
case SI_KCS:
new_smi->handlers = &kcs_smi_handlers;
break;
case SI_SMIC:
new_smi->handlers = &smic_smi_handlers;
break;
case SI_BT:
new_smi->handlers = &bt_smi_handlers;
break;
default:
/* No support for anything else yet. */
rv = -EIO;
goto out_err;
}
new_smi->si_num = smi_num;
/* Do this early so it's available for logs. */
if (!new_smi->io.dev) {
init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d",
new_smi->si_num);
/*
* If we don't already have a device from something
* else (like PCI), then register a new one.
*/
new_smi->pdev = platform_device_alloc("ipmi_si",
new_smi->si_num);
if (!new_smi->pdev) {
pr_err("Unable to allocate platform device\n");
rv = -ENOMEM;
goto out_err;
}
new_smi->io.dev = &new_smi->pdev->dev;
new_smi->io.dev->driver = &ipmi_platform_driver.driver;
/* Nulled by device_add() */
new_smi->io.dev->init_name = init_name;
}
/* Allocate the state machine's data and initialize it. */
new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
if (!new_smi->si_sm) {
rv = -ENOMEM;
goto out_err;
}
new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm,
&new_smi->io);
/* Now that we know the I/O size, we can set up the I/O. */
rv = new_smi->io.io_setup(&new_smi->io);
if (rv) {
dev_err(new_smi->io.dev, "Could not set up I/O space\n");
goto out_err;
}
/* Do low-level detection first. */
if (new_smi->handlers->detect(new_smi->si_sm)) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"Interface detection failed\n");
rv = -ENODEV;
goto out_err;
}
/*
* Attempt a get device id command. If it fails, we probably
* don't have a BMC here.
*/
rv = try_get_dev_id(new_smi);
if (rv) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"There appears to be no BMC at this location\n");
goto out_err;
}
setup_oem_data_handler(new_smi);
setup_xaction_handlers(new_smi);
check_for_broken_irqs(new_smi);
new_smi->waiting_msg = NULL;
new_smi->curr_msg = NULL;
atomic_set(&new_smi->req_events, 0);
new_smi->run_to_completion = false;
for (i = 0; i < SI_NUM_STATS; i++)
atomic_set(&new_smi->stats[i], 0);
new_smi->interrupt_disabled = true;
atomic_set(&new_smi->need_watch, 0);
rv = try_enable_event_buffer(new_smi);
if (rv == 0)
new_smi->has_event_buffer = true;
/*
* Start clearing the flags before we enable interrupts or the
* timer to avoid racing with the timer.
*/
start_clear_flags(new_smi);
/*
* IRQ is defined to be set when non-zero. req_events will
* cause a global flags check that will enable interrupts.
*/
if (new_smi->io.irq) {
new_smi->interrupt_disabled = false;
atomic_set(&new_smi->req_events, 1);
}
if (new_smi->pdev && !new_smi->pdev_registered) {
rv = platform_device_add(new_smi->pdev);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register system interface device: %d\n",
rv);
goto out_err;
}
new_smi->pdev_registered = true;
}
dev_set_drvdata(new_smi->io.dev, new_smi);
rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to add device attributes: error %d\n",
rv);
goto out_err;
}
new_smi->dev_group_added = true;
rv = ipmi_register_smi(&handlers,
new_smi,
new_smi->io.dev,
new_smi->io.slave_addr);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register device: error %d\n",
rv);
goto out_err;
}
/* Don't increment till we know we have succeeded. */
smi_num++;
dev_info(new_smi->io.dev, "IPMI %s interface initialized\n",
si_to_str[new_smi->io.si_type]);
WARN_ON(new_smi->io.dev->init_name != NULL);
out_err:
kfree(init_name);
return rv;
}
Commit Message: ipmi_si: fix use-after-free of resource->name
When we excute the following commands, we got oops
rmmod ipmi_si
cat /proc/ioports
[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478
[ 1623.482382] Mem abort info:
[ 1623.482383] ESR = 0x96000007
[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits
[ 1623.482386] SET = 0, FnV = 0
[ 1623.482387] EA = 0, S1PTW = 0
[ 1623.482388] Data abort info:
[ 1623.482389] ISV = 0, ISS = 0x00000007
[ 1623.482390] CM = 0, WnR = 0
[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66
[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000
[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP
[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]
[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168
[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)
[ 1623.553684] pc : string+0x28/0x98
[ 1623.557040] lr : vsnprintf+0x368/0x5e8
[ 1623.560837] sp : ffff000013213a80
[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5
[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049
[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5
[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000
[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000
[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff
[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000
[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000
[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000
[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000
[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f
[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe
[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478
[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000
[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff
[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)
[ 1623.651592] Call trace:
[ 1623.654068] string+0x28/0x98
[ 1623.657071] vsnprintf+0x368/0x5e8
[ 1623.660517] seq_vprintf+0x70/0x98
[ 1623.668009] seq_printf+0x7c/0xa0
[ 1623.675530] r_show+0xc8/0xf8
[ 1623.682558] seq_read+0x330/0x440
[ 1623.689877] proc_reg_read+0x78/0xd0
[ 1623.697346] __vfs_read+0x60/0x1a0
[ 1623.704564] vfs_read+0x94/0x150
[ 1623.711339] ksys_read+0x6c/0xd8
[ 1623.717939] __arm64_sys_read+0x24/0x30
[ 1623.725077] el0_svc_common+0x120/0x148
[ 1623.732035] el0_svc_handler+0x30/0x40
[ 1623.738757] el0_svc+0x8/0xc
[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)
[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---
[ 1623.760871] Kernel panic - not syncing: Fatal exception
[ 1623.768935] SMP: stopping secondary CPUs
[ 1623.775718] Kernel Offset: disabled
[ 1623.781998] CPU features: 0x002,21006008
[ 1623.788777] Memory Limit: none
[ 1623.798329] Starting crashdump kernel...
[ 1623.805202] Bye!
If io_setup is called successful in try_smi_init() but try_smi_init()
goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()
will not be called while removing module. It leads to the resource that
allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of
resource is freed while removing the module. It causes use-after-free
when cat /proc/ioports.
Fix this by calling io_cleanup() while try_smi_init() goes to out_err.
and don't call io_cleanup() until io_setup() returns successful to avoid
warning prints.
Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit")
Cc: [email protected]
Reported-by: NuoHan Qiao <[email protected]>
Suggested-by: Corey Minyard <[email protected]>
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int __peernet2id(struct net *net, struct net *peer)
{
bool no = false;
return __peernet2id_alloc(net, peer, &no);
}
Commit Message: net: Fix double free and memory corruption in get_net_ns_by_id()
(I can trivially verify that that idr_remove in cleanup_net happens
after the network namespace count has dropped to zero --EWB)
Function get_net_ns_by_id() does not check for net::count
after it has found a peer in netns_ids idr.
It may dereference a peer, after its count has already been
finaly decremented. This leads to double free and memory
corruption:
put_net(peer) rtnl_lock()
atomic_dec_and_test(&peer->count) [count=0] ...
__put_net(peer) get_net_ns_by_id(net, id)
spin_lock(&cleanup_list_lock)
list_add(&net->cleanup_list, &cleanup_list)
spin_unlock(&cleanup_list_lock)
queue_work() peer = idr_find(&net->netns_ids, id)
| get_net(peer) [count=1]
| ...
| (use after final put)
v ...
cleanup_net() ...
spin_lock(&cleanup_list_lock) ...
list_replace_init(&cleanup_list, ..) ...
spin_unlock(&cleanup_list_lock) ...
... ...
... put_net(peer)
... atomic_dec_and_test(&peer->count) [count=0]
... spin_lock(&cleanup_list_lock)
... list_add(&net->cleanup_list, &cleanup_list)
... spin_unlock(&cleanup_list_lock)
... queue_work()
... rtnl_unlock()
rtnl_lock() ...
for_each_net(tmp) { ...
id = __peernet2id(tmp, peer) ...
spin_lock_irq(&tmp->nsid_lock) ...
idr_remove(&tmp->netns_ids, id) ...
... ...
net_drop_ns() ...
net_free(peer) ...
} ...
|
v
cleanup_net()
...
(Second free of peer)
Also, put_net() on the right cpu may reorder with left's cpu
list_replace_init(&cleanup_list, ..), and then cleanup_list
will be corrupted.
Since cleanup_net() is executed in worker thread, while
put_net(peer) can happen everywhere, there should be
enough time for concurrent get_net_ns_by_id() to pick
the peer up, and the race does not seem to be unlikely.
The patch fixes the problem in standard way.
(Also, there is possible problem in peernet2id_alloc(), which requires
check for net::count under nsid_lock and maybe_get_net(peer), but
in current stable kernel it's used under rtnl_lock() and it has to be
safe. Openswitch begun to use peernet2id_alloc(), and possibly it should
be fixed too. While this is not in stable kernel yet, so I'll send
a separate message to netdev@ later).
Cc: Nicolas Dichtel <[email protected]>
Signed-off-by: Kirill Tkhai <[email protected]>
Fixes: 0c7aecd4bde4 "netns: add rtnl cmd to add and get peer netns ids"
Reviewed-by: Andrey Ryabinin <[email protected]>
Reviewed-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Acked-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[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: std::unique_ptr<net::test_server::HttpResponse> AddChromeProxyHeader(
const net::test_server::HttpRequest& request) {
base::AutoLock auto_lock(lock_);
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
if (!header_.empty())
response->AddCustomHeader(chrome_proxy_header(), header_);
if (!location_header_.empty())
response->AddCustomHeader("Location", location_header_);
if (response_hook_)
response_hook_.Run(response.get());
bool use_special_status_code = false;
if (request.headers.find("Host") != request.headers.end()) {
const GURL kOriginUrl(
base::StrCat({"http://", request.headers.find("Host")->second +
request.GetURL().path()}));
if (!special_host_port_pair_.IsEmpty() &&
net::HostPortPair::FromURL(kOriginUrl) == special_host_port_pair_) {
use_special_status_code = true;
}
}
if (use_special_status_code) {
response->set_code(special_status_code_);
} else {
response->set_code(status_code_);
}
response->set_content(kPrimaryResponse);
response->set_content_type("text/plain");
return response;
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(int argc, char *argv[])
{
libettercap_init();
ef_globals_alloc();
select_text_interface();
libettercap_ui_init();
/* etterfilter copyright */
fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n",
PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);
/* initialize the line number */
EF_GBL->lineno = 1;
/* getopt related parsing... */
parse_options(argc, argv);
/* set the input for source file */
if (EF_GBL_OPTIONS->source_file) {
yyin = fopen(EF_GBL_OPTIONS->source_file, "r");
if (yyin == NULL)
FATAL_ERROR("Input file not found !");
} else {
FATAL_ERROR("No source file.");
}
/* no buffering */
setbuf(yyin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
/* load the tables in etterfilter.tbl */
load_tables();
/* load the constants in etterfilter.cnt */
load_constants();
/* print the message */
fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file);
fflush(stdout);
ef_debug(1, "\n");
/* begin the parsing */
if (yyparse() == 0)
fprintf(stdout, " done.\n\n");
else
fprintf(stdout, "\n\nThe script contains errors...\n\n");
/* write to file */
if (write_output() != E_SUCCESS)
FATAL_ERROR("Cannot write output file (%s)", EF_GBL_OPTIONS->output_file);
ef_globals_free();
return 0;
}
Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782)
CWE ID: CWE-125
Target: 1
Example 2:
Code: CIFSSMBUnixSetPathInfo(const int xid, struct cifs_tcon *tcon, char *fileName,
const struct cifs_unix_set_info_args *args,
const struct nls_table *nls_codepage, int remap)
{
TRANSACTION2_SPI_REQ *pSMB = NULL;
TRANSACTION2_SPI_RSP *pSMBr = NULL;
int name_len;
int rc = 0;
int bytes_returned = 0;
FILE_UNIX_BASIC_INFO *data_offset;
__u16 params, param_offset, offset, count, byte_count;
cFYI(1, "In SetUID/GID/Mode");
setPermsRetry:
rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,
(void **) &pSMBr);
if (rc)
return rc;
if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
name_len =
cifsConvertToUCS((__le16 *) pSMB->FileName, fileName,
PATH_MAX, nls_codepage, remap);
name_len++; /* trailing null */
name_len *= 2;
} else { /* BB improve the check for buffer overruns BB */
name_len = strnlen(fileName, PATH_MAX);
name_len++; /* trailing null */
strncpy(pSMB->FileName, fileName, name_len);
}
params = 6 + name_len;
count = sizeof(FILE_UNIX_BASIC_INFO);
pSMB->MaxParameterCount = cpu_to_le16(2);
/* BB find max SMB PDU from sess structure BB */
pSMB->MaxDataCount = cpu_to_le16(1000);
pSMB->MaxSetupCount = 0;
pSMB->Reserved = 0;
pSMB->Flags = 0;
pSMB->Timeout = 0;
pSMB->Reserved2 = 0;
param_offset = offsetof(struct smb_com_transaction2_spi_req,
InformationLevel) - 4;
offset = param_offset + params;
data_offset =
(FILE_UNIX_BASIC_INFO *) ((char *) &pSMB->hdr.Protocol +
offset);
memset(data_offset, 0, count);
pSMB->DataOffset = cpu_to_le16(offset);
pSMB->ParameterOffset = cpu_to_le16(param_offset);
pSMB->SetupCount = 1;
pSMB->Reserved3 = 0;
pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);
byte_count = 3 /* pad */ + params + count;
pSMB->ParameterCount = cpu_to_le16(params);
pSMB->DataCount = cpu_to_le16(count);
pSMB->TotalParameterCount = pSMB->ParameterCount;
pSMB->TotalDataCount = pSMB->DataCount;
pSMB->InformationLevel = cpu_to_le16(SMB_SET_FILE_UNIX_BASIC);
pSMB->Reserved4 = 0;
inc_rfc1001_len(pSMB, byte_count);
cifs_fill_unix_set_info(data_offset, args);
pSMB->ByteCount = cpu_to_le16(byte_count);
rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
(struct smb_hdr *) pSMBr, &bytes_returned, 0);
if (rc)
cFYI(1, "SetPathInfo (perms) returned %d", rc);
cifs_buf_release(pSMB);
if (rc == -EAGAIN)
goto setPermsRetry;
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: static unsigned int transit_hash_key_make(void *p)
{
const struct transit *transit = p;
return jhash(transit->val, transit->length, 0);
}
Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined
Signed-off-by: Lou Berger <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
int len;
u32 max_blocksize = svc_max_payload(rqstp);
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ntohl(*p++);
args->count = ntohl(*p++);
len = args->count = min(args->count, max_blocksize);
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
if (!args->buffer)
args->buffer = page_address(p);
len -= PAGE_SIZE;
}
return xdr_argsize_check(rqstp, p);
}
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: 1
Example 2:
Code: void SyncTest::TriggerTransientError() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/transienterror";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Transient error",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_layoutget *lgp)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops =
nfsd4_layout_ops[lgp->lg_layout_type];
__be32 *p;
dprintk("%s: err %d\n", __func__, nfserr);
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t));
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* we always set return-on-close */
*p++ = cpu_to_be32(lgp->lg_sid.si_generation);
p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque,
sizeof(stateid_opaque_t));
*p++ = cpu_to_be32(1); /* we always return a single layout */
p = xdr_encode_hyper(p, lgp->lg_seg.offset);
p = xdr_encode_hyper(p, lgp->lg_seg.length);
*p++ = cpu_to_be32(lgp->lg_seg.iomode);
*p++ = cpu_to_be32(lgp->lg_layout_type);
nfserr = ops->encode_layoutget(xdr, lgp);
out:
kfree(lgp->lg_content);
return nfserr;
}
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: SSH_PACKET_CALLBACK(ssh_packet_kexdh_init){
int rc;
(void)type;
(void)user;
SSH_LOG(SSH_LOG_PACKET,"Received SSH_MSG_KEXDH_INIT");
if(session->dh_handshake_state != DH_STATE_INIT){
SSH_LOG(SSH_LOG_RARE,"Invalid state for SSH_MSG_KEXDH_INIT");
goto error;
}
switch(session->next_crypto->kex_type){
case SSH_KEX_DH_GROUP1_SHA1:
case SSH_KEX_DH_GROUP14_SHA1:
rc=ssh_server_kexdh_init(session, packet);
break;
#ifdef HAVE_ECDH
case SSH_KEX_ECDH_SHA2_NISTP256:
rc = ssh_server_ecdh_init(session, packet);
break;
#endif
#ifdef HAVE_CURVE25519
case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG:
rc = ssh_server_curve25519_init(session, packet);
break;
#endif
default:
ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_kexdh_init");
rc = SSH_ERROR;
}
if (rc == SSH_ERROR)
session->session_state = SSH_SESSION_STATE_ERROR;
error:
return SSH_PACKET_USED;
}
Commit Message:
CWE ID:
Target: 1
Example 2:
Code: void CL_OpenURL( const char *url ) {
if ( !url || !strlen( url ) ) {
Com_Printf( "%s", CL_TranslateStringBuf( "invalid/empty URL\n" ) );
return;
}
Sys_OpenURL( url, qtrue );
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AudioNode::Dispose() {
DCHECK(IsMainThread());
#if DEBUG_AUDIONODE_REFERENCES
fprintf(stderr, "[%16p]: %16p: %2d: AudioNode::dispose %16p\n", context(),
this, Handler().GetNodeType(), handler_.get());
#endif
BaseAudioContext::GraphAutoLocker locker(context());
Handler().Dispose();
if (context()->HasRealtimeConstraint()) {
context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
std::move(handler_));
} else {
if (context()->ContextState() == BaseAudioContext::kRunning) {
context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
std::move(handler_));
}
}
}
Commit Message: Revert "Keep AudioHandlers alive until they can be safely deleted."
This reverts commit 071df33edf2c8b4375fa432a83953359f93ea9e4.
Reason for revert:
This CL seems to cause an AudioNode leak on the Linux leak bot.
The log is:
https://ci.chromium.org/buildbot/chromium.webkit/WebKit%20Linux%20Trusty%20Leak/14252
* webaudio/AudioNode/audionode-connect-method-chaining.html
* webaudio/Panner/pannernode-basic.html
* webaudio/dom-exceptions.html
Original change's description:
> Keep AudioHandlers alive until they can be safely deleted.
>
> When an AudioNode is disposed, the handler is also disposed. But add
> the handler to the orphan list so that the handler stays alive until
> the context can safely delete it. If we don't do this, the handler
> may get deleted while the audio thread is processing the handler (due
> to, say, channel count changes and such).
>
> For an realtime context, always save the handler just in case the
> audio thread is running after the context is marked as closed (because
> the audio thread doesn't instantly stop when requested).
>
> For an offline context, only need to do this when the context is
> running because the context is guaranteed to be stopped if we're not
> in the running state. Hence, there's no possibility of deleting the
> handler while the graph is running.
>
> This is a revert of
> https://chromium-review.googlesource.com/c/chromium/src/+/860779, with
> a fix for the leak.
>
> Bug: 780919
> Change-Id: Ifb6b5fcf3fbc373f5779256688731245771da33c
> Reviewed-on: https://chromium-review.googlesource.com/862723
> Reviewed-by: Hongchan Choi <[email protected]>
> Commit-Queue: Raymond Toy <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#528829}
[email protected],[email protected]
Change-Id: Ibf406bf6ed34ea1f03e86a64a1e5ba6de0970c6f
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 780919
Reviewed-on: https://chromium-review.googlesource.com/863402
Reviewed-by: Taiju Tsuiki <[email protected]>
Commit-Queue: Taiju Tsuiki <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528888}
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: DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)
{
int i;
int ret = 0;
DefragInit();
/*
* Build the packets.
*/
int id = 1;
Packet *packets[17];
memset(packets, 0x00, sizeof(packets));
/*
* Original fragments.
*/
/* A*24 at 0. */
packets[0] = BuildTestPacket(id, 0, 1, 'A', 24);
/* B*15 at 32. */
packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16);
/* C*24 at 48. */
packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24);
/* D*8 at 80. */
packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8);
/* E*16 at 104. */
packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16);
/* F*24 at 120. */
packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24);
/* G*16 at 144. */
packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16);
/* H*16 at 160. */
packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16);
/* I*8 at 176. */
packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8);
/*
* Overlapping subsequent fragments.
*/
/* J*32 at 8. */
packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32);
/* K*24 at 48. */
packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24);
/* L*24 at 72. */
packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24);
/* M*24 at 96. */
packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24);
/* N*8 at 128. */
packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8);
/* O*8 at 152. */
packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8);
/* P*8 at 160. */
packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8);
/* Q*16 at 176. */
packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16);
default_policy = policy;
/* Send all but the last. */
for (i = 0; i < 9; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
goto end;
}
}
int overlap = 0;
for (; i < 16; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) {
overlap++;
}
}
if (!overlap) {
goto end;
}
/* And now the last one. */
Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);
if (reassembled == NULL) {
goto end;
}
if (IPV4_GET_HLEN(reassembled) != 20) {
goto end;
}
if (IPV4_GET_IPLEN(reassembled) != 20 + 192) {
goto end;
}
if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) {
goto end;
}
SCFree(reassembled);
/* Make sure all frags were returned back to the pool. */
if (defrag_context->frag_pool->outstanding != 0) {
goto end;
}
ret = 1;
end:
for (i = 0; i < 17; i++) {
SCFree(packets[i]);
}
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
Target: 1
Example 2:
Code: static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int ret = 0;
if (sk == p->exclude_sk)
goto out;
if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
goto out;
if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
ret = 1;
goto out;
}
sk->sk_err = p->code;
sk->sk_error_report(sk);
out:
return ret;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void HTMLFormControlElement::reset() {
setAutofilled(false);
resetImpl();
}
Commit Message: Form validation: Do not show validation bubble if the page is invisible.
BUG=673163
Review-Url: https://codereview.chromium.org/2572813003
Cr-Commit-Position: refs/heads/master@{#438476}
CWE ID: CWE-1021
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: bool decode(const SharedBuffer& data, bool onlySize)
{
m_decodingSizeOnly = onlySize;
unsigned newByteCount = data.size() - m_bufferLength;
unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
m_info.src->bytes_in_buffer += newByteCount;
m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
if (m_bytesToSkip)
skipBytes(m_bytesToSkip);
m_bufferLength = data.size();
if (setjmp(m_err.setjmp_buffer))
return m_decoder->setFailed();
switch (m_state) {
case JPEG_HEADER:
if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
return false; // I/O suspension.
switch (m_info.jpeg_color_space) {
case JCS_GRAYSCALE:
case JCS_RGB:
case JCS_YCbCr:
m_info.out_color_space = rgbOutputColorSpace();
#if defined(TURBO_JPEG_RGB_SWIZZLE)
if (m_info.saw_JFIF_marker)
break;
if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
m_info.out_color_space = JCS_RGB;
#endif
break;
case JCS_CMYK:
case JCS_YCCK:
m_info.out_color_space = JCS_CMYK;
break;
default:
return m_decoder->setFailed();
}
m_state = JPEG_START_DECOMPRESS;
if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
return false;
m_decoder->setOrientation(readImageOrientation(info()));
#if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE)
if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space))
m_info.out_color_space = JCS_RGB;
#endif
#if USE(QCMSLIB)
if (!m_decoder->ignoresGammaAndColorProfile()) {
ColorProfile colorProfile = readColorProfile(info());
createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space));
#if defined(TURBO_JPEG_RGB_SWIZZLE)
if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
m_info.out_color_space = JCS_EXT_RGBA;
#endif
}
#endif
m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
jpeg_calc_output_dimensions(&m_info);
m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1);
if (m_decodingSizeOnly) {
m_bufferLength -= m_info.src->bytes_in_buffer;
m_info.src->bytes_in_buffer = 0;
return true;
}
case JPEG_START_DECOMPRESS:
m_info.dct_method = dctMethod();
m_info.dither_mode = ditherMode();
m_info.do_fancy_upsampling = doFancyUpsampling();
m_info.enable_2pass_quant = false;
m_info.do_block_smoothing = true;
if (!jpeg_start_decompress(&m_info))
return false; // I/O suspension.
m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
case JPEG_DECOMPRESS_SEQUENTIAL:
if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
if (!m_decoder->outputScanlines())
return false; // I/O suspension.
ASSERT(m_info.output_scanline == m_info.output_height);
m_state = JPEG_DONE;
}
case JPEG_DECOMPRESS_PROGRESSIVE:
if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
int status;
do {
status = jpeg_consume_input(&m_info);
} while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
for (;;) {
if (!m_info.output_scanline) {
int scan = m_info.input_scan_number;
if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
--scan;
if (!jpeg_start_output(&m_info, scan))
return false; // I/O suspension.
}
if (m_info.output_scanline == 0xffffff)
m_info.output_scanline = 0;
if (!m_decoder->outputScanlines()) {
if (!m_info.output_scanline)
m_info.output_scanline = 0xffffff;
return false; // I/O suspension.
}
if (m_info.output_scanline == m_info.output_height) {
if (!jpeg_finish_output(&m_info))
return false; // I/O suspension.
if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
break;
m_info.output_scanline = 0;
}
}
m_state = JPEG_DONE;
}
case JPEG_DONE:
return jpeg_finish_decompress(&m_info);
case JPEG_ERROR:
return m_decoder->setFailed();
}
return true;
}
Commit Message: Progressive JPEG outputScanlines() calls should handle failure
outputScanlines() can fail and delete |this|, so any attempt to access
members thereafter should be avoided. Copy the decoder pointer member,
and use that copy to detect and handle the failure case.
BUG=232763
[email protected]
Review URL: https://codereview.chromium.org/14844003
git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: DataUseUserData::~DataUseUserData() {}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
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: int sctp_verify_asconf(const struct sctp_association *asoc,
struct sctp_paramhdr *param_hdr, void *chunk_end,
struct sctp_paramhdr **errp) {
sctp_addip_param_t *asconf_param;
union sctp_params param;
int length, plen;
param.v = (sctp_paramhdr_t *) param_hdr;
while (param.v <= chunk_end - sizeof(sctp_paramhdr_t)) {
length = ntohs(param.p->length);
*errp = param.p;
if (param.v > chunk_end - length ||
length < sizeof(sctp_paramhdr_t))
return 0;
switch (param.p->type) {
case SCTP_PARAM_ADD_IP:
case SCTP_PARAM_DEL_IP:
case SCTP_PARAM_SET_PRIMARY:
asconf_param = (sctp_addip_param_t *)param.v;
plen = ntohs(asconf_param->param_hdr.length);
if (plen < sizeof(sctp_addip_param_t) +
sizeof(sctp_paramhdr_t))
return 0;
break;
case SCTP_PARAM_SUCCESS_REPORT:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
if (length != sizeof(sctp_addip_param_t))
return 0;
break;
default:
break;
}
param.v += WORD_ROUND(length);
}
if (param.v != chunk_end)
return 0;
return 1;
}
Commit Message: net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks
Commit 6f4c618ddb0 ("SCTP : Add paramters validity check for
ASCONF chunk") added basic verification of ASCONF chunks, however,
it is still possible to remotely crash a server by sending a
special crafted ASCONF chunk, even up to pre 2.6.12 kernels:
skb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768
head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950
end:0x440 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:129!
[...]
Call Trace:
<IRQ>
[<ffffffff8144fb1c>] skb_put+0x5c/0x70
[<ffffffffa01ea1c3>] sctp_addto_chunk+0x63/0xd0 [sctp]
[<ffffffffa01eadaf>] sctp_process_asconf+0x1af/0x540 [sctp]
[<ffffffff8152d025>] ? _read_unlock_bh+0x15/0x20
[<ffffffffa01e0038>] sctp_sf_do_asconf+0x168/0x240 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffff8147645d>] ? fib_rules_lookup+0xad/0xf0
[<ffffffffa01e6b22>] ? sctp_cmp_addr_exact+0x32/0x40 [sctp]
[<ffffffffa01e8393>] sctp_assoc_bh_rcv+0xd3/0x180 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff81496ded>] ip_local_deliver_finish+0xdd/0x2d0
[<ffffffff81497078>] ip_local_deliver+0x98/0xa0
[<ffffffff8149653d>] ip_rcv_finish+0x12d/0x440
[<ffffffff81496ac5>] ip_rcv+0x275/0x350
[<ffffffff8145c88b>] __netif_receive_skb+0x4ab/0x750
[<ffffffff81460588>] netif_receive_skb+0x58/0x60
This can be triggered e.g., through a simple scripted nmap
connection scan injecting the chunk after the handshake, for
example, ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
------------------ ASCONF; UNKNOWN ------------------>
... where ASCONF chunk of length 280 contains 2 parameters ...
1) Add IP address parameter (param length: 16)
2) Add/del IP address parameter (param length: 255)
... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the
Address Parameter in the ASCONF chunk is even missing, too.
This is just an example and similarly-crafted ASCONF chunks
could be used just as well.
The ASCONF chunk passes through sctp_verify_asconf() as all
parameters passed sanity checks, and after walking, we ended
up successfully at the chunk end boundary, and thus may invoke
sctp_process_asconf(). Parameter walking is done with
WORD_ROUND() to take padding into account.
In sctp_process_asconf()'s TLV processing, we may fail in
sctp_process_asconf_param() e.g., due to removal of the IP
address that is also the source address of the packet containing
the ASCONF chunk, and thus we need to add all TLVs after the
failure to our ASCONF response to remote via helper function
sctp_add_asconf_response(), which basically invokes a
sctp_addto_chunk() adding the error parameters to the given
skb.
When walking to the next parameter this time, we proceed
with ...
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
... instead of the WORD_ROUND()'ed length, thus resulting here
in an off-by-one that leads to reading the follow-up garbage
parameter length of 12336, and thus throwing an skb_over_panic
for the reply when trying to sctp_addto_chunk() next time,
which implicitly calls the skb_put() with that length.
Fix it by using sctp_walk_params() [ which is also used in
INIT parameter processing ] macro in the verification *and*
in ASCONF processing: it will make sure we don't spill over,
that we walk parameters WORD_ROUND()'ed. Moreover, we're being
more defensive and guard against unknown parameter types and
missized addresses.
Joint work with Vlad Yasevich.
Fixes: b896b82be4ae ("[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg >= regsz) {
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
Commit Message: Fix #6836 - oob write in dex
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __udp6_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
const struct in6_addr *saddr, const struct in6_addr *daddr,
struct udp_table *udptable)
{
struct sock *sk, *stack[256 / sizeof(struct sock *)];
const struct udphdr *uh = udp_hdr(skb);
struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest));
int dif;
unsigned int i, count = 0;
spin_lock(&hslot->lock);
sk = sk_nulls_head(&hslot->head);
dif = inet6_iif(skb);
sk = udp_v6_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif);
while (sk) {
stack[count++] = sk;
sk = udp_v6_mcast_next(net, sk_nulls_next(sk), uh->dest, daddr,
uh->source, saddr, dif);
if (unlikely(count == ARRAY_SIZE(stack))) {
if (!sk)
break;
flush_stack(stack, count, skb, ~0);
count = 0;
}
}
/*
* before releasing the lock, we must take reference on sockets
*/
for (i = 0; i < count; i++)
sock_hold(stack[i]);
spin_unlock(&hslot->lock);
if (count) {
flush_stack(stack, count, skb, count - 1);
for (i = 0; i < count; i++)
sock_put(stack[i]);
} else {
kfree_skb(skb);
}
return 0;
}
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:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 bool is_exception(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-388
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: monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != NULL) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
/* Update with new address */
if (options.compression) {
ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void rds_tcp_destroy_conns(void)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
/* avoid calling conn_destroy with irqs off */
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn))
list_move_tail(&tc->t_tcp_node, &tmp_list);
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
Commit Message: net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().
When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.
In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.
Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.
rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <[email protected]>
==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721
CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0x120/0x188 lib/dump_stack.c:113
print_address_description+0x68/0x278 mm/kasan/report.c:253
kasan_report_error mm/kasan/report.c:351 [inline]
kasan_report+0x21c/0x348 mm/kasan/report.c:409
__asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
__sock_create+0x4f8/0x770 net/socket.c:1276
sock_create_kern+0x50/0x68 net/socket.c:1322
rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
Allocated by task 687:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2705 [inline]
slab_alloc mm/slub.c:2713 [inline]
kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
kmem_cache_zalloc include/linux/slab.h:697 [inline]
net_alloc net/core/net_namespace.c:384 [inline]
copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
ksys_unshare+0x340/0x628 kernel/fork.c:2577
__do_sys_unshare kernel/fork.c:2645 [inline]
__se_sys_unshare kernel/fork.c:2643 [inline]
__arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960
Freed by task 264:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
__kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
slab_free_hook mm/slub.c:1370 [inline]
slab_free_freelist_hook mm/slub.c:1397 [inline]
slab_free mm/slub.c:2952 [inline]
kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
net_free net/core/net_namespace.c:400 [inline]
net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
net_drop_ns net/core/net_namespace.c:406 [inline]
cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
The buggy address belongs to the object at ffff8003496a3f80
which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply,
uint8_t* p_reply_end) {
uint8_t *p, *p_start, *p_end, *p_param_len;
uint8_t type;
uint32_t seq_len;
uint16_t param_len, lists_byte_count = 0;
bool cont_request_needed = false;
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("process_service_search_attr_rsp");
#endif
/* If p_reply is NULL, we were called for the initial read */
if (p_reply) {
if (p_reply + 4 /* transaction ID and length */ + sizeof(lists_byte_count) >
p_reply_end) {
android_errorWriteLog(0x534e4554, "79884292");
sdp_disconnect(p_ccb, SDP_INVALID_PDU_SIZE);
return;
}
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("ID & len: 0x%02x-%02x-%02x-%02x", p_reply[0], p_reply[1],
p_reply[2], p_reply[3]);
#endif
/* Skip transaction ID and length */
p_reply += 4;
BE_STREAM_TO_UINT16(lists_byte_count, p_reply);
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("lists_byte_count:%d", lists_byte_count);
#endif
/* Copy the response to the scratchpad. First, a safety check on the length
*/
if ((p_ccb->list_len + lists_byte_count) > SDP_MAX_LIST_BYTE_COUNT) {
sdp_disconnect(p_ccb, SDP_INVALID_PDU_SIZE);
return;
}
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("list_len: %d, list_byte_count: %d", p_ccb->list_len,
lists_byte_count);
#endif
if (p_reply + lists_byte_count + 1 /* continuation */ > p_reply_end) {
android_errorWriteLog(0x534e4554, "79884292");
sdp_disconnect(p_ccb, SDP_INVALID_PDU_SIZE);
return;
}
if (p_ccb->rsp_list == NULL)
p_ccb->rsp_list = (uint8_t*)osi_malloc(SDP_MAX_LIST_BYTE_COUNT);
memcpy(&p_ccb->rsp_list[p_ccb->list_len], p_reply, lists_byte_count);
p_ccb->list_len += lists_byte_count;
p_reply += lists_byte_count;
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("list_len: %d(search_attr_rsp)", p_ccb->list_len);
/* Check if we need to request a continuation */
SDP_TRACE_WARNING("*p_reply:%d(%d)", *p_reply, SDP_MAX_CONTINUATION_LEN);
#endif
if (*p_reply) {
if (*p_reply > SDP_MAX_CONTINUATION_LEN) {
sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE);
return;
}
cont_request_needed = true;
}
}
#if (SDP_DEBUG_RAW == TRUE)
SDP_TRACE_WARNING("cont_request_needed:%d", cont_request_needed);
#endif
/* If continuation request (or first time request) */
if ((cont_request_needed) || (!p_reply)) {
BT_HDR* p_msg = (BT_HDR*)osi_malloc(SDP_DATA_BUF_SIZE);
uint8_t* p;
p_msg->offset = L2CAP_MIN_OFFSET;
p = p_start = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET;
/* Build a service search request packet */
UINT8_TO_BE_STREAM(p, SDP_PDU_SERVICE_SEARCH_ATTR_REQ);
UINT16_TO_BE_STREAM(p, p_ccb->transaction_id);
p_ccb->transaction_id++;
/* Skip the length, we need to add it at the end */
p_param_len = p;
p += 2;
/* Build the UID sequence. */
#if (SDP_BROWSE_PLUS == TRUE)
p = sdpu_build_uuid_seq(p, 1,
&p_ccb->p_db->uuid_filters[p_ccb->cur_uuid_idx]);
#else
p = sdpu_build_uuid_seq(p, p_ccb->p_db->num_uuid_filters,
p_ccb->p_db->uuid_filters);
#endif
/* Max attribute byte count */
UINT16_TO_BE_STREAM(p, sdp_cb.max_attr_list_size);
/* If no attribute filters, build a wildcard attribute sequence */
if (p_ccb->p_db->num_attr_filters)
p = sdpu_build_attrib_seq(p, p_ccb->p_db->attr_filters,
p_ccb->p_db->num_attr_filters);
else
p = sdpu_build_attrib_seq(p, NULL, 0);
/* No continuation for first request */
if (p_reply) {
if ((p_reply + *p_reply + 1) <= p_reply_end) {
memcpy(p, p_reply, *p_reply + 1);
p += *p_reply + 1;
} else {
android_errorWriteLog(0x534e4554, "68161546");
}
} else
UINT8_TO_BE_STREAM(p, 0);
/* Go back and put the parameter length into the buffer */
param_len = p - p_param_len - 2;
UINT16_TO_BE_STREAM(p_param_len, param_len);
/* Set the length of the SDP data in the buffer */
p_msg->len = p - p_start;
L2CA_DataWrite(p_ccb->connection_id, p_msg);
/* Start inactivity timer */
alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS,
sdp_conn_timer_timeout, p_ccb);
return;
}
/*******************************************************************/
/* We now have the full response, which is a sequence of sequences */
/*******************************************************************/
#if (SDP_RAW_DATA_INCLUDED == TRUE)
SDP_TRACE_WARNING("process_service_search_attr_rsp");
sdp_copy_raw_data(p_ccb, true);
#endif
p = &p_ccb->rsp_list[0];
/* The contents is a sequence of attribute sequences */
type = *p++;
if ((type >> 3) != DATA_ELE_SEQ_DESC_TYPE) {
SDP_TRACE_WARNING("SDP - Wrong type: 0x%02x in attr_rsp", type);
return;
}
p = sdpu_get_len_from_type(p, type, &seq_len);
p_end = &p_ccb->rsp_list[p_ccb->list_len];
if ((p + seq_len) != p_end) {
sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE);
return;
}
while (p < p_end) {
p = save_attr_seq(p_ccb, p, &p_ccb->rsp_list[p_ccb->list_len]);
if (!p) {
sdp_disconnect(p_ccb, SDP_DB_FULL);
return;
}
}
/* Since we got everything we need, disconnect the call */
sdp_disconnect(p_ccb, SDP_SUCCESS);
}
Commit Message: Fix copy length calculation in sdp_copy_raw_data
Test: compilation
Bug: 110216176
Change-Id: Ic4a19c9f0fe8cd592bc6c25dcec7b1da49ff7459
(cherry picked from commit 23aa15743397b345f3d948289fe90efa2a2e2b3e)
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: static v8::Handle<v8::Value> overloadedMethod11Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod11");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
EXCEPTION_BLOCK(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
TestObj::overloadedMethod1(arg);
return v8::Handle<v8::Value>();
}
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: DocumentAvailableInMainFrame() {
devtools_bindings_->DocumentAvailableInMainFrame();
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
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 LayerTreeCoordinator::syncLayerFilters(WebLayerID id, const FilterOperations& filters)
{
m_shouldSyncFrame = true;
m_webPage->send(Messages::LayerTreeCoordinatorProxy::SetCompositingLayerFilters(id, filters));
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip)
{
CPUState *cs = CPU(cpu);
CPUX86State *env = &cpu->env;
VAPICHandlers *handlers;
uint8_t opcode[2];
uint32_t imm32;
target_ulong current_pc = 0;
target_ulong current_cs_base = 0;
uint32_t current_flags = 0;
if (smp_cpus == 1) {
handlers = &s->rom_state.up;
} else {
handlers = &s->rom_state.mp;
}
if (!kvm_enabled()) {
cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base,
¤t_flags);
}
pause_all_vcpus();
cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0);
switch (opcode[0]) {
case 0x89: /* mov r32 to r/m32 */
patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */
patch_call(s, cpu, ip + 1, handlers->set_tpr);
break;
case 0x8b: /* mov r/m32 to r32 */
patch_byte(cpu, ip, 0x90);
patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]);
break;
case 0xa1: /* mov abs to eax */
patch_call(s, cpu, ip, handlers->get_tpr[0]);
break;
case 0xa3: /* mov eax to abs */
patch_call(s, cpu, ip, handlers->set_tpr_eax);
break;
case 0xc7: /* mov imm32, r/m32 (c7/0) */
patch_byte(cpu, ip, 0x68); /* push imm32 */
cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0);
cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1);
patch_call(s, cpu, ip + 5, handlers->set_tpr);
break;
case 0xff: /* push r/m32 */
patch_byte(cpu, ip, 0x50); /* push eax */
patch_call(s, cpu, ip + 1, handlers->get_tpr_stack);
break;
default:
abort();
}
resume_all_vcpus();
if (!kvm_enabled()) {
tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1);
cpu_resume_from_signal(cs, NULL);
}
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void mptsas_save_request(QEMUFile *f, SCSIRequest *sreq)
{
MPTSASRequest *req = sreq->hba_private;
int i;
qemu_put_buffer(f, (unsigned char *)&req->scsi_io, sizeof(req->scsi_io));
qemu_put_be32(f, req->qsg.nsg);
for (i = 0; i < req->qsg.nsg; i++) {
qemu_put_be64(f, req->qsg.sg[i].base);
qemu_put_be64(f, req->qsg.sg[i].len);
}
}
Commit Message:
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: pvscsi_build_sglist(PVSCSIState *s, PVSCSIRequest *r)
{
PCIDevice *d = PCI_DEVICE(s);
pci_dma_sglist_init(&r->sgl, d, 1);
if (r->req.flags & PVSCSI_FLAG_CMD_WITH_SG_LIST) {
pvscsi_convert_sglist(r);
} else {
qemu_sglist_add(&r->sgl, r->req.dataAddr, r->req.dataLen);
}
}
Commit Message:
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadRLAImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
typedef struct _WindowFrame
{
short
left,
right,
bottom,
top;
} WindowFrame;
typedef struct _RLAInfo
{
WindowFrame
window,
active_window;
short
frame,
storage_type,
number_channels,
number_matte_channels,
number_auxiliary_channels,
revision;
char
gamma[16],
red_primary[24],
green_primary[24],
blue_primary[24],
white_point[24];
ssize_t
job_number;
char
name[128],
description[128],
program[64],
machine[32],
user[32],
date[20],
aspect[24],
aspect_ratio[8],
chan[32];
short
field;
char
time[12],
filter[32];
short
bits_per_channel,
matte_type,
matte_bits,
auxiliary_type,
auxiliary_bits;
char
auxiliary[32],
space[36];
ssize_t
next;
} RLAInfo;
Image
*image;
int
channel,
length,
runlength;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
*scanlines,
y;
RLAInfo
rla_info;
unsigned char
byte;
/*
Open image file.
*/
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);
}
rla_info.window.left=(short) ReadBlobMSBShort(image);
rla_info.window.right=(short) ReadBlobMSBShort(image);
rla_info.window.bottom=(short) ReadBlobMSBShort(image);
rla_info.window.top=(short) ReadBlobMSBShort(image);
rla_info.active_window.left=(short) ReadBlobMSBShort(image);
rla_info.active_window.right=(short) ReadBlobMSBShort(image);
rla_info.active_window.bottom=(short) ReadBlobMSBShort(image);
rla_info.active_window.top=(short) ReadBlobMSBShort(image);
rla_info.frame=(short) ReadBlobMSBShort(image);
rla_info.storage_type=(short) ReadBlobMSBShort(image);
rla_info.number_channels=(short) ReadBlobMSBShort(image);
rla_info.number_matte_channels=(short) ReadBlobMSBShort(image);
if (rla_info.number_channels == 0)
rla_info.number_channels=3;
rla_info.number_channels+=rla_info.number_matte_channels;
rla_info.number_auxiliary_channels=(short) ReadBlobMSBShort(image);
rla_info.revision=(short) ReadBlobMSBShort(image);
count=ReadBlob(image,16,(unsigned char *) rla_info.gamma);
count=ReadBlob(image,24,(unsigned char *) rla_info.red_primary);
count=ReadBlob(image,24,(unsigned char *) rla_info.green_primary);
count=ReadBlob(image,24,(unsigned char *) rla_info.blue_primary);
count=ReadBlob(image,24,(unsigned char *) rla_info.white_point);
rla_info.job_number=(int) ReadBlobMSBLong(image);
count=ReadBlob(image,128,(unsigned char *) rla_info.name);
count=ReadBlob(image,128,(unsigned char *) rla_info.description);
rla_info.description[127]='\0';
count=ReadBlob(image,64,(unsigned char *) rla_info.program);
count=ReadBlob(image,32,(unsigned char *) rla_info.machine);
count=ReadBlob(image,32,(unsigned char *) rla_info.user);
count=ReadBlob(image,20,(unsigned char *) rla_info.date);
count=ReadBlob(image,24,(unsigned char *) rla_info.aspect);
count=ReadBlob(image,8,(unsigned char *) rla_info.aspect_ratio);
count=ReadBlob(image,32,(unsigned char *) rla_info.chan);
rla_info.field=(short) ReadBlobMSBShort(image);
count=ReadBlob(image,12,(unsigned char *) rla_info.time);
count=ReadBlob(image,32,(unsigned char *) rla_info.filter);
rla_info.bits_per_channel=(short) ReadBlobMSBShort(image);
rla_info.matte_type=(short) ReadBlobMSBShort(image);
rla_info.matte_bits=(short) ReadBlobMSBShort(image);
rla_info.auxiliary_type=(short) ReadBlobMSBShort(image);
rla_info.auxiliary_bits=(short) ReadBlobMSBShort(image);
count=ReadBlob(image,32,(unsigned char *) rla_info.auxiliary);
count=ReadBlob(image,36,(unsigned char *) rla_info.space);
if ((size_t) count != 36)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
rla_info.next=(int) ReadBlobMSBLong(image);
/*
Initialize image structure.
*/
image->matte=rla_info.number_matte_channels != 0 ? MagickTrue : MagickFalse;
image->columns=1UL*rla_info.active_window.right-rla_info.active_window.left+1;
image->rows=1UL*rla_info.active_window.top-rla_info.active_window.bottom+1;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
scanlines=(ssize_t *) AcquireQuantumMemory(image->rows,sizeof(*scanlines));
if (scanlines == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (*rla_info.description != '\0')
(void) SetImageProperty(image,"comment",(char *) rla_info.description);
/*
Read offsets to each scanline data.
*/
for (i=0; i < (ssize_t) image->rows; i++)
scanlines[i]=(int) ReadBlobMSBLong(image);
/*
Read image data.
*/
x=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
offset=SeekBlob(image,scanlines[image->rows-y-1],SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (channel=0; channel < (int) rla_info.number_channels; channel++)
{
length=(int) ReadBlobMSBShort(image);
while (length > 0)
{
byte=(unsigned char) ReadBlobByte(image);
runlength=byte;
if (byte > 127)
runlength=byte-256;
length--;
if (length == 0)
break;
if (runlength < 0)
{
while (runlength < 0)
{
q=GetAuthenticPixels(image,(ssize_t) (x % image->columns),
(ssize_t) (y % image->rows),1,1,exception);
if (q == (PixelPacket *) NULL)
break;
byte=(unsigned char) ReadBlobByte(image);
length--;
switch (channel)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(byte));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum(byte));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(byte));
break;
}
case 3:
default:
{
SetPixelAlpha(q,ScaleCharToQuantum(byte));
break;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
x++;
runlength++;
}
continue;
}
byte=(unsigned char) ReadBlobByte(image);
length--;
runlength++;
do
{
q=GetAuthenticPixels(image,(ssize_t) (x % image->columns),
(ssize_t) (y % image->rows),1,1,exception);
if (q == (PixelPacket *) NULL)
break;
switch (channel)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(byte));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum(byte));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(byte));
break;
}
case 3:
default:
{
SetPixelAlpha(q,ScaleCharToQuantum(byte));
break;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
x++;
runlength--;
}
while (runlength > 0);
}
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
dbgregs->dr6 = vcpu->arch.dr6;
dbgregs->dr7 = vcpu->arch.dr7;
dbgregs->flags = 0;
memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: spnego_gss_inquire_cred_by_oid(
OM_uint32 *minor_status,
const gss_cred_id_t cred_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 ret;
spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle;
gss_cred_id_t mcred;
mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred;
ret = gss_inquire_cred_by_oid(minor_status,
mcred,
desired_object,
data_set);
return (ret);
}
Commit Message: Fix null deref in SPNEGO acceptor [CVE-2014-4344]
When processing a continuation token, acc_ctx_cont was dereferencing
the initial byte of the token without checking the length. This could
result in a null dereference.
CVE-2014-4344:
In MIT krb5 1.5 and newer, an unauthenticated or partially
authenticated remote attacker can cause a NULL dereference and
application crash during a SPNEGO negotiation by sending an empty
token as the second or later context token from initiator to acceptor.
The attacker must provide at least one valid context token in the
security context negotiation before sending the empty token. This can
be done by an unauthenticated attacker by forcing SPNEGO to
renegotiate the underlying mechanism, or by using IAKERB to wrap an
unauthenticated AS-REQ as the first token.
CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: CVE summary, CVSSv2 vector]
(cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b)
ticket: 7970
version_fixed: 1.12.2
status: resolved
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: int sas_smp_get_phy_events(struct sas_phy *phy)
{
int res;
u8 *req;
u8 *resp;
struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent);
struct domain_device *dev = sas_find_dev_by_rphy(rphy);
req = alloc_smp_req(RPEL_REQ_SIZE);
if (!req)
return -ENOMEM;
resp = alloc_smp_resp(RPEL_RESP_SIZE);
if (!resp) {
kfree(req);
return -ENOMEM;
}
req[1] = SMP_REPORT_PHY_ERR_LOG;
req[9] = phy->number;
res = smp_execute_task(dev, req, RPEL_REQ_SIZE,
resp, RPEL_RESP_SIZE);
if (!res)
goto out;
phy->invalid_dword_count = scsi_to_u32(&resp[12]);
phy->running_disparity_error_count = scsi_to_u32(&resp[16]);
phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]);
phy->phy_reset_problem_count = scsi_to_u32(&resp[24]);
out:
kfree(resp);
return res;
}
Commit Message: scsi: libsas: fix memory leak in sas_smp_get_phy_events()
We've got a memory leak with the following producer:
while true;
do cat /sys/class/sas_phy/phy-1:0:12/invalid_dword_count >/dev/null;
done
The buffer req is allocated and not freed after we return. Fix it.
Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver")
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: chenqilin <[email protected]>
CC: chenxiang <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-772
Target: 1
Example 2:
Code: static int nfs41_free_stateid(struct nfs_server *server,
nfs4_stateid *stateid,
struct rpc_cred *cred)
{
struct rpc_task *task;
int ret;
task = _nfs41_free_stateid(server, stateid, cred, true);
if (IS_ERR(task))
return PTR_ERR(task);
ret = rpc_wait_for_completion_task(task);
if (!ret)
ret = task->tk_status;
rpc_put_task(task);
return ret;
}
Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client
---Steps to Reproduce--
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
<nfs-client>
# mount -t nfs nfs-server:/nfs/ /mnt/
# ll /mnt/*/
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
# service nfs restart
<nfs-client>
# ll /mnt/*/ --->>>>> oops here
[ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null)
[ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0
[ 5123.104131] Oops: 0000 [#1]
[ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd]
[ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214
[ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014
[ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000
[ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246
[ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240
[ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908
[ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000
[ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800
[ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240
[ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000
[ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0
[ 5123.112888] Stack:
[ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000
[ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6
[ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800
[ 5123.115264] Call Trace:
[ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4]
[ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4]
[ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4]
[ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0
[ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70
[ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33
[ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.122308] RSP <ffff88005877fdb8>
[ 5123.122942] CR2: 0000000000000000
Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops")
Cc: [email protected] # v3.13+
Signed-off-by: Kinglong Mee <[email protected]>
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: bool IsAllowed(const scoped_refptr<const Extension>& extension,
const GURL& url,
PermittedFeature feature,
int tab_id) {
const PermissionsData* permissions_data = extension->permissions_data();
bool script = permissions_data->CanAccessPage(extension.get(), url, tab_id,
nullptr) &&
permissions_data->CanRunContentScriptOnPage(
extension.get(), url, tab_id, nullptr);
bool capture = HasTabsPermission(extension, tab_id) &&
permissions_data->CanCaptureVisiblePage(tab_id, NULL);
switch (feature) {
case PERMITTED_SCRIPT_ONLY:
return script && !capture;
case PERMITTED_CAPTURE_ONLY:
return capture && !script;
case PERMITTED_BOTH:
return script && capture;
case PERMITTED_NONE:
return !script && !capture;
}
NOTREACHED();
return false;
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
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: vrrp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len,
register const u_char *bp2, int ttl)
{
int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */
const char *type_s;
ND_TCHECK(bp[0]);
version = (bp[0] & 0xf0) >> 4;
type = bp[0] & 0x0f;
type_s = tok2str(type2str, "unknown type (%u)", type);
ND_PRINT((ndo, "VRRPv%u, %s", version, type_s));
if (ttl != 255)
ND_PRINT((ndo, ", (ttl %u)", ttl));
if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)
return;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2]));
ND_TCHECK(bp[5]);
if (version == 2) {
auth_type = bp[4];
ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type)));
ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len));
} else { /* version == 3 */
uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];
ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len));
}
if (ndo->ndo_vflag) {
int naddrs = bp[3];
int i;
char c;
if (version == 2 && ND_TTEST2(bp[0], len)) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
if (in_cksum(vec, 1))
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
if (version == 3 && ND_TTEST2(bp[0], len)) {
uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,
len, len, IPPROTO_VRRP);
if (cksum)
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
ND_PRINT((ndo, ", addrs"));
if (naddrs > 1)
ND_PRINT((ndo, "(%d)", naddrs));
ND_PRINT((ndo, ":"));
c = ' ';
bp += 8;
for (i = 0; i < naddrs; i++) {
ND_TCHECK(bp[3]);
ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp)));
c = ',';
bp += 4;
}
if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */
ND_TCHECK(bp[7]);
ND_PRINT((ndo, " auth \""));
if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
}
}
return;
trunc:
ND_PRINT((ndo, "[|vrrp]"));
}
Commit Message: (for 4.9.3) CVE-2018-14463/VRRP: Add a missing bounds check
In vrrp_print().
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: void NotifyRedirectOnUI(int render_process_id,
int render_frame_host,
scoped_ptr<ResourceRedirectDetails> details) {
RenderFrameHostImpl* host =
RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
if (!web_contents)
return;
web_contents->DidGetRedirectForResourceRequest(host, *details.get());
}
Commit Message: Block a compromised renderer from reusing request ids.
BUG=578882
Review URL: https://codereview.chromium.org/1608573002
Cr-Commit-Position: refs/heads/master@{#372547}
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 Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
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*MaxTextExtent, 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*MaxTextExtent,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) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%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) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
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/122
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
if (copy_file("/etc/skel/.zshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.zshrc");
}
}
else { //
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
if (copy_file("/etc/skel/.cshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.cshrc");
}
}
else { //
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
if (copy_file("/etc/skel/.bashrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.bashrc");
}
}
free(fname);
}
}
Commit Message: replace copy_file with copy_file_as_user
CWE ID: CWE-269
Target: 1
Example 2:
Code: void GLES2Implementation::SetActiveURLCHROMIUM(const char* url) {
DCHECK(url);
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glSetActiveURLCHROMIUM(" << url);
if (last_active_url_ == url)
return;
last_active_url_ = url;
static constexpr uint32_t kMaxStrLen = 1024;
size_t len = strlen(url);
if (len == 0)
return;
SetBucketContents(kResultBucketId, url,
base::CheckMin(len, kMaxStrLen).ValueOrDie());
helper_->SetActiveURLCHROMIUM(kResultBucketId);
helper_->SetBucketSize(kResultBucketId, 0);
}
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 int nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
struct page *page, unsigned int len, struct iattr *sattr)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_symlink(dir, dentry, page,
len, sattr),
&exception);
} while (exception.retry);
return err;
}
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: static void dump_completed_IO(struct inode * inode)
{
#ifdef EXT4_DEBUG
struct list_head *cur, *before, *after;
ext4_io_end_t *io, *io0, *io1;
if (list_empty(&EXT4_I(inode)->i_completed_io_list)){
ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino);
return;
}
ext4_debug("Dump inode %lu completed_io list \n", inode->i_ino);
list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){
cur = &io->list;
before = cur->prev;
io0 = container_of(before, ext4_io_end_t, list);
after = cur->next;
io1 = container_of(after, ext4_io_end_t, list);
ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
io, inode->i_ino, io0, io1);
}
#endif
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
unsigned int keylen, ...)
{
struct sdesc *sdesc;
va_list argp;
unsigned int dlen;
unsigned char *data;
int ret;
sdesc = init_sdesc(hmacalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hmac_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_setkey(hmacalg, key, keylen);
if (ret < 0)
goto out;
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
va_start(argp, keylen);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
data = va_arg(argp, unsigned char *);
if (data == NULL) {
ret = -EINVAL;
break;
}
ret = crypto_shash_update(&sdesc->shash, data, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, digest);
out:
kfree(sdesc);
return ret;
}
Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key
If a user key gets negatively instantiated, an error code is cached in the
payload area. A negatively instantiated key may be then be positively
instantiated by updating it with valid data. However, the ->update key
type method must be aware that the error code may be there.
The following may be used to trigger the bug in the user key type:
keyctl request2 user user "" @u
keyctl add user user "a" @u
which manifests itself as:
BUG: unable to handle kernel paging request at 00000000ffffff8a
IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
PGD 7cc30067 PUD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000
RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280
[<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246
RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001
RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82
RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000
R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82
R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700
FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0
Stack:
ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82
ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5
ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620
Call Trace:
[<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136
[<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129
[< inline >] __key_update security/keys/key.c:730
[<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908
[< inline >] SYSC_add_key security/keys/keyctl.c:125
[<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60
[<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185
Note the error code (-ENOKEY) in EDX.
A similar bug can be tripped by:
keyctl request2 trusted user "" @u
keyctl add trusted user "a" @u
This should also affect encrypted keys - but that has to be correctly
parameterised or it will fail with EINVAL before getting to the bit that
will crashes.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long mkvparser::UnserializeFloat(
IMkvReader* pReader,
long long pos,
long long size_,
double& result)
{
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) //error
return status;
if (size == 4)
{
union
{
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;)
{
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
}
else
{
assert(size == 8);
union
{
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;)
{
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
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: OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 1
Example 2:
Code: void SoftMPEG2::logVersion() {
ivd_ctl_getversioninfo_ip_t s_ctl_ip;
ivd_ctl_getversioninfo_op_t s_ctl_op;
UWORD8 au1_buf[512];
IV_API_CALL_STATUS_T status;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_GETVERSION;
s_ctl_ip.u4_size = sizeof(ivd_ctl_getversioninfo_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_getversioninfo_op_t);
s_ctl_ip.pv_version_buffer = au1_buf;
s_ctl_ip.u4_version_buffer_size = sizeof(au1_buf);
status = ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op);
if (status != IV_SUCCESS) {
ALOGE("Error in getting version number: 0x%x",
s_ctl_op.u4_error_code);
} else {
ALOGV("Ittiam decoder version number: %s",
(char *)s_ctl_ip.pv_version_buffer);
}
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
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 WebGLRenderingContextBase::validateProgram(WebGLProgram* program) {
if (!ValidateWebGLProgramOrShader("validateProgram", program))
return;
ContextGL()->ValidateProgram(ObjectOrZero(program));
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PlatformSensorLinux::PlatformSensorLinux(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider,
const SensorInfoLinux* sensor_device,
scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner)
: PlatformSensor(type, std::move(mapping), provider),
default_configuration_(
PlatformSensorConfiguration(sensor_device->device_frequency)),
reporting_mode_(sensor_device->reporting_mode),
polling_thread_task_runner_(std::move(polling_thread_task_runner)),
weak_factory_(this) {
sensor_reader_ = SensorReader::Create(
sensor_device, weak_factory_.GetWeakPtr(), task_runner_);
}
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
Target: 1
Example 2:
Code: static void Begin(const wchar_t* const protocols[],
const base::Closure& on_finished_callback) {
delete instance_;
instance_ = new OpenSystemSettingsHelper(protocols, on_finished_callback);
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
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: LayerTreeHostTestContinuousDrawWhenCreatingVisibleTiles()
: playback_allowed_event_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::SIGNALED) {}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
Output: | 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> postMessageCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestActiveDOMObject.postMessage");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder());
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
imp->postMessage(message);
return v8::Handle<v8::Value>();
}
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: BGD_DECLARE(void) gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
{
gdIOCtx *out = gdNewFileCtx (outFile);
if (out == NULL) return;
_gdImageGd2 (im, out, cs, fmt);
out->gd_free (out);
}
Commit Message: gd2: handle corrupt images better (CVE-2016-3074)
Make sure we do some range checking on corrupted chunks.
Thanks to Hans Jerry Illikainen <[email protected]> for indepth report
and reproducer information. Made for easy test case writing :).
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: pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
Commit Message: CVE-2017-13018/PGM: Add a missing bounds check.
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
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 noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
Commit Message: KEYS: close race between key lookup and freeing
When a key is being garbage collected, it's key->user would get put before
the ->destroy() callback is called, where the key is removed from it's
respective tracking structures.
This leaves a key hanging in a semi-invalid state which leaves a window open
for a different task to try an access key->user. An example is
find_keyring_by_name() which would dereference key->user for a key that is
in the process of being garbage collected (where key->user was freed but
->destroy() wasn't called yet - so it's still present in the linked list).
This would cause either a panic, or corrupt memory.
Fixes CVE-2014-9529.
Signed-off-by: Sasha Levin <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void put_ctx(struct perf_event_context *ctx)
{
if (atomic_dec_and_test(&ctx->refcount)) {
if (ctx->parent_ctx)
put_ctx(ctx->parent_ctx);
if (ctx->task)
put_task_struct(ctx->task);
call_rcu(&ctx->rcu_head, free_ctx);
}
}
Commit Message: perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <[email protected]>
Tested-by: Sasha Levin <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Signed-off-by: Ingo Molnar <[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 __sys_sendmsg(struct socket *sock, struct msghdr __user *msg,
struct msghdr *msg_sys, unsigned flags,
struct used_address *used_address)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct sockaddr_storage address;
struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
unsigned char ctl[sizeof(struct cmsghdr) + 20]
__attribute__ ((aligned(sizeof(__kernel_size_t))));
/* 20 is size of ipv6_pktinfo */
unsigned char *ctl_buf = ctl;
int err, ctl_len, iov_size, total_len;
err = -EFAULT;
if (MSG_CMSG_COMPAT & flags) {
if (get_compat_msghdr(msg_sys, msg_compat))
return -EFAULT;
} else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr)))
return -EFAULT;
/* do not move before msg_sys is valid */
err = -EMSGSIZE;
if (msg_sys->msg_iovlen > UIO_MAXIOV)
goto out;
/* Check whether to allocate the iovec area */
err = -ENOMEM;
iov_size = msg_sys->msg_iovlen * sizeof(struct iovec);
if (msg_sys->msg_iovlen > UIO_FASTIOV) {
iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL);
if (!iov)
goto out;
}
/* This will also move the address data into kernel space */
if (MSG_CMSG_COMPAT & flags) {
err = verify_compat_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
} else
err = verify_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
if (err < 0)
goto out_freeiov;
total_len = err;
err = -ENOBUFS;
if (msg_sys->msg_controllen > INT_MAX)
goto out_freeiov;
ctl_len = msg_sys->msg_controllen;
if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
err =
cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
sizeof(ctl));
if (err)
goto out_freeiov;
ctl_buf = msg_sys->msg_control;
ctl_len = msg_sys->msg_controllen;
} else if (ctl_len) {
if (ctl_len > sizeof(ctl)) {
ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
if (ctl_buf == NULL)
goto out_freeiov;
}
err = -EFAULT;
/*
* Careful! Before this, msg_sys->msg_control contains a user pointer.
* Afterwards, it will be a kernel pointer. Thus the compiler-assisted
* checking falls down on this.
*/
if (copy_from_user(ctl_buf,
(void __user __force *)msg_sys->msg_control,
ctl_len))
goto out_freectl;
msg_sys->msg_control = ctl_buf;
}
msg_sys->msg_flags = flags;
if (sock->file->f_flags & O_NONBLOCK)
msg_sys->msg_flags |= MSG_DONTWAIT;
/*
* If this is sendmmsg() and current destination address is same as
* previously succeeded address, omit asking LSM's decision.
* used_address->name_len is initialized to UINT_MAX so that the first
* destination address never matches.
*/
if (used_address && used_address->name_len == msg_sys->msg_namelen &&
!memcmp(&used_address->name, msg->msg_name,
used_address->name_len)) {
err = sock_sendmsg_nosec(sock, msg_sys, total_len);
goto out_freectl;
}
err = sock_sendmsg(sock, msg_sys, total_len);
/*
* If this is sendmmsg() and sending to current destination address was
* successful, remember it.
*/
if (used_address && err >= 0) {
used_address->name_len = msg_sys->msg_namelen;
memcpy(&used_address->name, msg->msg_name,
used_address->name_len);
}
out_freectl:
if (ctl_buf != ctl)
sock_kfree_s(sock->sk, ctl_buf, ctl_len);
out_freeiov:
if (iov != iovstack)
sock_kfree_s(sock->sk, iov, iov_size);
out:
return err;
}
Commit Message: sendmmsg/sendmsg: fix unsafe user pointer access
Dereferencing a user pointer directly from kernel-space without going
through the copy_from_user family of functions is a bad idea. Two of
such usages can be found in the sendmsg code path called from sendmmsg,
added by
commit c71d8ebe7a4496fb7231151cb70a6baa0cb56f9a upstream.
commit 5b47b8038f183b44d2d8ff1c7d11a5c1be706b34 in the 3.0-stable tree.
Usages are performed through memcmp() and memcpy() directly. Fix those
by using the already copied msg_sys structure instead of the __user *msg
structure. Note that msg_sys can be set to NULL by verify_compat_iovec()
or verify_iovec(), which requires additional NULL pointer checks.
Signed-off-by: Mathieu Desnoyers <[email protected]>
Signed-off-by: David Goulet <[email protected]>
CC: Tetsuo Handa <[email protected]>
CC: Anton Blanchard <[email protected]>
CC: David S. Miller <[email protected]>
CC: stable <[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: bool BackingStoreGtk::CopyFromBackingStore(const gfx::Rect& rect,
skia::PlatformCanvas* output) {
base::TimeTicks begin_time = base::TimeTicks::Now();
if (visual_depth_ < 24) {
return false;
}
const int width = std::min(size().width(), rect.width());
const int height = std::min(size().height(), rect.height());
XImage* image;
XShmSegmentInfo shminfo; // Used only when shared memory is enabled.
if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) {
Visual* visual = static_cast<Visual*>(visual_);
memset(&shminfo, 0, sizeof(shminfo));
image = XShmCreateImage(display_, visual, 32,
ZPixmap, NULL, &shminfo, width, height);
if (!image) {
return false;
}
if (image->bytes_per_line == 0 || image->height == 0 ||
static_cast<size_t>(image->height) >
(std::numeric_limits<size_t>::max() / image->bytes_per_line)) {
XDestroyImage(image);
return false;
}
shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height,
IPC_CREAT|0666);
if (shminfo.shmid == -1) {
XDestroyImage(image);
return false;
}
void* mapped_memory = shmat(shminfo.shmid, NULL, SHM_RDONLY);
shmctl(shminfo.shmid, IPC_RMID, 0);
if (mapped_memory == (void*)-1) {
XDestroyImage(image);
return false;
}
shminfo.shmaddr = image->data = static_cast<char*>(mapped_memory);
if (!XShmAttach(display_, &shminfo) ||
!XShmGetImage(display_, pixmap_, image, rect.x(), rect.y(),
AllPlanes)) {
DestroySharedImage(display_, image, &shminfo);
return false;
}
} else {
image = XGetImage(display_, pixmap_,
rect.x(), rect.y(), width, height,
AllPlanes, ZPixmap);
}
if (!output->initialize(width, height, true) ||
image->bits_per_pixel != 32) {
if (shared_memory_support_ != ui::SHARED_MEMORY_NONE)
DestroySharedImage(display_, image, &shminfo);
else
XDestroyImage(image);
return false;
}
SkBitmap bitmap = skia::GetTopDevice(*output)->accessBitmap(true);
SkAutoLockPixels alp(bitmap);
for (int y = 0; y < height; y++) {
const uint32* src_row = reinterpret_cast<uint32*>(
&image->data[image->bytes_per_line * y]);
uint32* dest_row = bitmap.getAddr32(0, y);
for (int x = 0; x < width; ++x, ++dest_row) {
*dest_row = src_row[x] | 0xff000000;
}
}
if (shared_memory_support_ != ui::SHARED_MEMORY_NONE)
DestroySharedImage(display_, image, &shminfo);
else
XDestroyImage(image);
HISTOGRAM_TIMES("BackingStore.RetrievalFromX",
base::TimeTicks::Now() - begin_time);
return true;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
unsigned int len;
__u16 num_blocks;
__u16 num_dup_tsns;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
Commit Message: sctp: Use correct sideffect command in duplicate cookie handling
When SCTP is done processing a duplicate cookie chunk, it tries
to delete a newly created association. For that, it has to set
the right association for the side-effect processing to work.
However, when it uses the SCTP_CMD_NEW_ASOC command, that performs
more work then really needed (like hashing the associationa and
assigning it an id) and there is no point to do that only to
delete the association as a next step. In fact, it also creates
an impossible condition where an association may be found by
the getsockopt() call, and that association is empty. This
causes a crash in some sctp getsockopts.
The solution is rather simple. We simply use SCTP_CMD_SET_ASOC
command that doesn't have all the overhead and does exactly
what we need.
Reported-by: Karl Heiss <[email protected]>
Tested-by: Karl Heiss <[email protected]>
CC: Neil Horman <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[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 Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
{
if (!isContextThread()) {
postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
if (Page* page = this->page())
page->console()->addMessage(source, level, message, sourceURL, lineNumber, callStack, state, requestIdentifier);
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
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 read_boot(DOS_FS * fs)
{
struct boot_sector b;
unsigned total_sectors;
unsigned short logical_sector_size, sectors;
unsigned fat_length;
unsigned total_fat_entries;
off_t data_size;
fs_read(0, sizeof(b), &b);
logical_sector_size = GET_UNALIGNED_W(b.sector_size);
if (!logical_sector_size)
die("Logical sector size is zero.");
/* This was moved up because it's the first thing that will fail */
/* if the platform needs special handling of unaligned multibyte accesses */
/* but such handling isn't being provided. See GET_UNALIGNED_W() above. */
if (logical_sector_size & (SECTOR_SIZE - 1))
die("Logical sector size (%d bytes) is not a multiple of the physical "
"sector size.", logical_sector_size);
fs->cluster_size = b.cluster_size * logical_sector_size;
if (!fs->cluster_size)
die("Cluster size is zero.");
if (b.fats != 2 && b.fats != 1)
die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats);
fs->nfats = b.fats;
sectors = GET_UNALIGNED_W(b.sectors);
total_sectors = sectors ? sectors : le32toh(b.total_sect);
if (verbose)
printf("Checking we can access the last sector of the filesystem\n");
/* Can't access last odd sector anyway, so round down */
fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size,
logical_sector_size);
fat_length = le16toh(b.fat_length) ?
le16toh(b.fat_length) : le32toh(b.fat32_length);
fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size;
fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) *
logical_sector_size;
fs->root_entries = GET_UNALIGNED_W(b.dir_entries);
fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries <<
MSDOS_DIR_BITS,
logical_sector_size);
data_size = (off_t)total_sectors * logical_sector_size - fs->data_start;
fs->data_clusters = data_size / fs->cluster_size;
fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */
fs->fsinfo_start = 0; /* no FSINFO structure */
fs->free_clusters = -1; /* unknown */
if (!b.fat_length && b.fat32_length) {
fs->fat_bits = 32;
fs->root_cluster = le32toh(b.root_cluster);
if (!fs->root_cluster && fs->root_entries)
/* M$ hasn't specified this, but it looks reasonable: If
* root_cluster is 0 but there is a separate root dir
* (root_entries != 0), we handle the root dir the old way. Give a
* warning, but convertig to a root dir in a cluster chain seems
* to complex for now... */
printf("Warning: FAT32 root dir not in cluster chain! "
"Compatibility mode...\n");
else if (!fs->root_cluster && !fs->root_entries)
die("No root directory!");
else if (fs->root_cluster && fs->root_entries)
printf("Warning: FAT32 root dir is in a cluster chain, but "
"a separate root dir\n"
" area is defined. Cannot fix this easily.\n");
if (fs->data_clusters < FAT16_THRESHOLD)
printf("Warning: Filesystem is FAT32 according to fat_length "
"and fat32_length fields,\n"
" but has only %lu clusters, less than the required "
"minimum of %d.\n"
" This may lead to problems on some systems.\n",
(unsigned long)fs->data_clusters, FAT16_THRESHOLD);
check_fat_state_bit(fs, &b);
fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size;
check_backup_boot(fs, &b, logical_sector_size);
read_fsinfo(fs, &b, logical_sector_size);
} else if (!atari_format) {
/* On real MS-DOS, a 16 bit FAT is used whenever there would be too
* much clusers otherwise. */
fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12;
if (fs->data_clusters >= FAT16_THRESHOLD)
die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters);
check_fat_state_bit(fs, &b);
} else {
/* On Atari, things are more difficult: GEMDOS always uses 12bit FATs
* on floppies, and always 16 bit on harddisks. */
fs->fat_bits = 16; /* assume 16 bit FAT for now */
/* If more clusters than fat entries in 16-bit fat, we assume
* it's a real MSDOS FS with 12-bit fat. */
if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 ||
/* if it has one of the usual floppy sizes -> 12bit FAT */
(total_sectors == 720 || total_sectors == 1440 ||
total_sectors == 2880))
fs->fat_bits = 12;
}
/* On FAT32, the high 4 bits of a FAT entry are reserved */
fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits;
fs->fat_size = fat_length * logical_sector_size;
fs->label = calloc(12, sizeof(uint8_t));
if (fs->fat_bits == 12 || fs->fat_bits == 16) {
struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b;
if (b16->extended_sig == 0x29)
memmove(fs->label, b16->label, 11);
else
fs->label = NULL;
} else if (fs->fat_bits == 32) {
if (b.extended_sig == 0x29)
memmove(fs->label, &b.label, 11);
else
fs->label = NULL;
}
total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits;
if (fs->data_clusters > total_fat_entries - 2)
die("Filesystem has %u clusters but only space for %u FAT entries.",
fs->data_clusters, total_fat_entries - 2);
if (!fs->root_entries && !fs->root_cluster)
die("Root directory has zero size.");
if (fs->root_entries & (MSDOS_DPS - 1))
die("Root directory (%d entries) doesn't span an integral number of "
"sectors.", fs->root_entries);
if (logical_sector_size & (SECTOR_SIZE - 1))
die("Logical sector size (%d bytes) is not a multiple of the physical "
"sector size.", logical_sector_size);
#if 0 /* linux kernel doesn't check that either */
/* ++roman: On Atari, these two fields are often left uninitialized */
if (!atari_format && (!b.secs_track || !b.heads))
die("Invalid disk format in boot sector.");
#endif
if (verbose)
dump_boot(fs, &b, logical_sector_size);
}
Commit Message: read_boot(): Handle excessive FAT size specifications
The variable used for storing the FAT size (in bytes) was an unsigned
int. Since the size in sectors read from the BPB was not sufficiently
checked, this could end up being zero after multiplying it with the
sector size while some offsets still stayed excessive. Ultimately it
would cause segfaults when accessing FAT entries for which no memory
was allocated.
Make it more robust by changing the types used to store FAT size to
off_t and abort if there is no room for data clusters. Additionally
check that FAT size is not specified as zero.
Fixes #25 and fixes #26.
Reported-by: Hanno Böck
Signed-off-by: Andreas Bombe <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int hns_nic_net_up(struct net_device *ndev)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
struct hnae_handle *h = priv->ae_handle;
int i, j;
int ret;
ret = hns_nic_init_irq(priv);
if (ret != 0) {
netdev_err(ndev, "hns init irq failed! ret=%d\n", ret);
return ret;
}
for (i = 0; i < h->q_num * 2; i++) {
ret = hns_nic_ring_open(ndev, i);
if (ret)
goto out_has_some_queues;
}
ret = h->dev->ops->set_mac_addr(h, ndev->dev_addr);
if (ret)
goto out_set_mac_addr_err;
ret = h->dev->ops->start ? h->dev->ops->start(h) : 0;
if (ret)
goto out_start_err;
if (ndev->phydev)
phy_start(ndev->phydev);
clear_bit(NIC_STATE_DOWN, &priv->state);
(void)mod_timer(&priv->service_timer, jiffies + SERVICE_TIMER_HZ);
return 0;
out_start_err:
netif_stop_queue(ndev);
out_set_mac_addr_err:
out_has_some_queues:
for (j = i - 1; j >= 0; j--)
hns_nic_ring_close(ndev, j);
set_bit(NIC_STATE_DOWN, &priv->state);
return ret;
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Segment::AppendCluster(Cluster* pCluster)
{
assert(pCluster);
assert(pCluster->m_index >= 0);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
const long idx = pCluster->m_index;
assert(idx == m_clusterCount);
if (count >= size)
{
const long n = (size <= 0) ? 2048 : 2*size;
Cluster** const qq = new Cluster*[n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
if (m_clusterPreloadCount > 0)
{
assert(m_clusters);
Cluster** const p = m_clusters + m_clusterCount;
assert(*p);
assert((*p)->m_index < 0);
Cluster** q = p + m_clusterPreloadCount;
assert(q < (m_clusters + size));
for (;;)
{
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
Commit Message:
CWE ID: CWE-125
Target: 1
Example 2:
Code: LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& h)
{
LayoutUnit logicalHeight = -1;
if (!h.isAuto()) {
if (h.isFixed())
logicalHeight = h.value();
else if (h.isPercent())
logicalHeight = computePercentageLogicalHeight(h);
if (logicalHeight != -1) {
logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
return logicalHeight;
}
}
return logicalHeight;
}
Commit Message: Source/WebCore: Fix for bug 64046 - Wrong image height in absolutely positioned div in
relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
Test: fast/css/absolute-child-with-percent-height-inside-relative-parent.html
* rendering/RenderBox.cpp:
(WebCore::RenderBox::availableLogicalHeightUsing):
LayoutTests: Test to cover absolutely positioned child with percentage height
in relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
* fast/css/absolute-child-with-percent-height-inside-relative-parent-expected.txt: Added.
* fast/css/absolute-child-with-percent-height-inside-relative-parent.html: Added.
git-svn-id: svn://svn.chromium.org/blink/trunk@91533 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 ssize_t aac_show_monitor_version(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata;
int len, tmp;
tmp = le32_to_cpu(dev->adapter_info.monitorrev);
len = snprintf(buf, PAGE_SIZE, "%d.%d-%d[%d]\n",
tmp >> 24, (tmp >> 16) & 0xff, tmp & 0xff,
le32_to_cpu(dev->adapter_info.monitorbuild));
return len;
}
Commit Message: aacraid: missing capable() check in compat ioctl
In commit d496f94d22d1 ('[SCSI] aacraid: fix security weakness') we
added a check on CAP_SYS_RAWIO to the ioctl. The compat ioctls need the
check as well.
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[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: image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_tRNS_to_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: static RList *r_bin_wasm_get_code_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmCodeEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, j = 0, r = 0;
size_t n = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmCodeEntry))) {
return ret;
}
if (!(n = consume_u32 (buf + i, buf + len, &ptr->body_size, &i))) {
free (ptr);
return ret;
}
if (!(i + ptr->body_size - 1 < len)) {
free (ptr);
return ret;
}
j = i;
if (!(n = consume_u32 (buf + i, buf + len, &ptr->local_count, &i))) {
free (ptr);
return ret;
}
if ((n = consume_locals (buf + i, buf + len, ptr->local_count,ptr, &i)) < ptr->local_count) {
free (ptr);
return ret;
}
ptr->code = sec->payload_data + i;
ptr->len = ptr->body_size - (i - j);
i += ptr->len - 1; // consume bytecode
if (!(consume_u8 (buf + i, buf + len, &ptr->byte, &i))) {
free (ptr);
return ret;
}
if (ptr->byte != R_BIN_WASM_END_OF_CODE) {
free (ptr);
return ret;
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
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 userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (ACCESS_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
userfaultfd_ctx_put(new);
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, POLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
userfaultfd_ctx_put(ctx);
}
Commit Message: userfaultfd: non-cooperative: fix fork use after free
When reading the event from the uffd, we put it on a temporary
fork_event list to detect if we can still access it after releasing and
retaking the event_wqh.lock.
If fork aborts and removes the event from the fork_event all is fine as
long as we're still in the userfault read context and fork_event head is
still alive.
We've to put the event allocated in the fork kernel stack, back from
fork_event list-head to the event_wqh head, before returning from
userfaultfd_ctx_read, because the fork_event head lifetime is limited to
the userfaultfd_ctx_read stack lifetime.
Forgetting to move the event back to its event_wqh place then results in
__remove_wait_queue(&ctx->event_wqh, &ewq->wq); in
userfaultfd_event_wait_completion to remove it from a head that has been
already freed from the reader stack.
This could only happen if resolve_userfault_fork failed (for example if
there are no file descriptors available to allocate the fork uffd). If
it succeeded it was put back correctly.
Furthermore, after find_userfault_evt receives a fork event, the forked
userfault context in fork_nctx and uwq->msg.arg.reserved.reserved1 can
be released by the fork thread as soon as the event_wqh.lock is
released. Taking a reference on the fork_nctx before dropping the lock
prevents an use after free in resolve_userfault_fork().
If the fork side aborted and it already released everything, we still
try to succeed resolve_userfault_fork(), if possible.
Fixes: 893e26e61d04eac9 ("userfaultfd: non-cooperative: Add fork() event")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Mark Rutland <[email protected]>
Tested-by: Mark Rutland <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Cc: Mike Rapoport <[email protected]>
Cc: "Dr. David Alan Gilbert" <[email protected]>
Cc: Mike Kravetz <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
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: static void get_frame_stats(vpx_codec_ctx_t *ctx,
const vpx_image_t *img,
vpx_codec_pts_t pts,
unsigned int duration,
vpx_enc_frame_flags_t flags,
unsigned int deadline,
vpx_fixed_buf_t *stats) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
deadline);
if (res != VPX_CODEC_OK)
die_codec(ctx, "Failed to get frame stats.");
while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_STATS_PKT) {
const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf;
const size_t pkt_size = pkt->data.twopass_stats.sz;
stats->buf = realloc(stats->buf, stats->sz + pkt_size);
memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size);
stats->sz += pkt_size;
}
}
}
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: static void update_cursor(VirtIOGPU *g, struct virtio_gpu_update_cursor *cursor)
{
struct virtio_gpu_scanout *s;
bool move = cursor->hdr.type == VIRTIO_GPU_CMD_MOVE_CURSOR;
if (cursor->pos.scanout_id >= g->conf.max_outputs) {
return;
}
s = &g->scanout[cursor->pos.scanout_id];
trace_virtio_gpu_update_cursor(cursor->pos.scanout_id,
cursor->pos.x,
cursor->pos.y,
move ? "move" : "update",
cursor->resource_id);
if (!move) {
if (!s->current_cursor) {
s->current_cursor = cursor_alloc(64, 64);
}
s->current_cursor->hot_x = cursor->hot_x;
s->current_cursor->hot_y = cursor->hot_y;
if (cursor->resource_id > 0) {
VIRGL(g, update_cursor_data_virgl, update_cursor_data_simple,
g, s, cursor->resource_id);
}
dpy_cursor_define(s->con, s->current_cursor);
s->cursor = *cursor;
} else {
s->cursor.pos.x = cursor->pos.x;
s->cursor.pos.y = cursor->pos.y;
}
dpy_mouse_set(s->con, cursor->pos.x, cursor->pos.y,
cursor->resource_id ? 1 : 0);
}
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: AMediaCodecCryptoInfo *AMediaCodecCryptoInfo_new(
int numsubsamples,
uint8_t key[16],
uint8_t iv[16],
cryptoinfo_mode_t mode,
size_t *clearbytes,
size_t *encryptedbytes) {
size_t cryptosize = sizeof(AMediaCodecCryptoInfo) + sizeof(size_t) * numsubsamples * 2;
AMediaCodecCryptoInfo *ret = (AMediaCodecCryptoInfo*) malloc(cryptosize);
if (!ret) {
ALOGE("couldn't allocate %zu bytes", cryptosize);
return NULL;
}
ret->numsubsamples = numsubsamples;
memcpy(ret->key, key, 16);
memcpy(ret->iv, iv, 16);
ret->mode = mode;
ret->pattern.encryptBlocks = 0;
ret->pattern.skipBlocks = 0;
ret->clearbytes = (size_t*) (ret + 1); // point immediately after the struct
ret->encryptedbytes = ret->clearbytes + numsubsamples; // point after the clear sizes
memcpy(ret->clearbytes, clearbytes, numsubsamples * sizeof(size_t));
memcpy(ret->encryptedbytes, encryptedbytes, numsubsamples * sizeof(size_t));
return ret;
}
Commit Message: Check for overflow of crypto size
Bug: 111603051
Test: CTS
Change-Id: Ib5b1802b9b35769a25c16e2b977308cf7a810606
(cherry picked from commit d1fd02761236b35a336434367131f71bef7405c9)
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowDCMException(exception,message) \
{ \
if (data != (unsigned char *) NULL) \
data=(unsigned char *) RelinquishMagickMemory(data); \
if (stream_info != (DCMStreamInfo *) NULL) \
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \
ThrowReaderException((exception),(message)); \
}
char
explicit_vr[MaxTextExtent],
implicit_vr[MaxTextExtent],
magick[MaxTextExtent],
photometric[MaxTextExtent];
DCMInfo
info;
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
sequence,
use_explicit;
MagickOffsetType
offset;
register unsigned char
*p;
register ssize_t
i;
size_t
colors,
height,
length,
number_scenes,
quantum,
status,
width;
ssize_t
count,
scene;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
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);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
data=(unsigned char *) NULL;
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
info.polarity=MagickFalse;
info.scale=(Quantum *) NULL;
info.bits_allocated=8;
info.bytes_per_pixel=1;
info.depth=8;
info.mask=0xffff;
info.max_value=255UL;
info.samples_per_pixel=1;
info.signed_data=(~0UL);
info.significant_bits=0;
info.rescale=MagickFalse;
info.rescale_intercept=0.0;
info.rescale_slope=1.0;
info.window_center=0.0;
info.window_width=0.0;
data=(unsigned char *) NULL;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
number_scenes=1;
sequence=MagickFalse;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MaxTextExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MaxTextExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowDCMException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
info.samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
info.bits_allocated=(size_t) datum;
info.bytes_per_pixel=1;
if (datum > 8)
info.bytes_per_pixel=2;
info.depth=info.bits_allocated;
if (info.depth > 32)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.bits_allocated)-1;
image->depth=info.depth;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
info.significant_bits=(size_t) datum;
info.bytes_per_pixel=1;
if (info.significant_bits > 8)
info.bytes_per_pixel=2;
info.depth=info.significant_bits;
if (info.depth > 32)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.significant_bits)-1;
info.mask=(size_t) GetQuantumRange(info.significant_bits);
image->depth=info.depth;
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
info.signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
info.window_center=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
info.window_width=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
info.rescale_intercept=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
info.rescale_slope=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/info.bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (info.bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
info.polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (info.signed_data == 0xffff)
info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MaxTextExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property));
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(info.depth)+1);
info.scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*info.scale));
if (info.scale == (Quantum *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(info.depth);
for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++)
info.scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image)+8;
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=info.depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
break;
}
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelPacket *) NULL) &&
(info.samples_per_pixel == 1))
{
int
index;
size_t
one;
one=1;
if (colors == 0)
colors=one << info.depth;
if (AcquireImageColormap(image,colors) == MagickFalse)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(Quantum) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].green=(Quantum) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].blue=(Quantum) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(Quantum) index;
image->colormap[i].green=(Quantum) index;
image->colormap[i].blue=(Quantum) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
if (stream_info->segment_count > 1)
{
info.bytes_per_pixel=1;
info.depth=8;
if (stream_info->offset_count > 0)
(void) SeekBlob(image,stream_info->offsets[0]+
stream_info->segments[0],SEEK_SET);
}
}
if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) info.samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
default:
break;
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
/*
Convert DCM Medical image to pixel packets.
*/
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
info.window_width=0;
}
option=GetImageOption(image_info,"dcm:window");
if (option != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(option,&geometry_info);
if (flags & RhoValue)
info.window_center=geometry_info.rho;
if (flags & SigmaValue)
info.window_width=geometry_info.sigma;
info.rescale=MagickTrue;
}
option=GetImageOption(image_info,"dcm:rescale");
if (option != (char *) NULL)
info.rescale=IsStringTrue(option);
if ((info.window_center != 0) && (info.window_width == 0))
info.window_width=info.window_center;
status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception);
if ((status != MagickFalse) && (stream_info->segment_count > 1))
{
if (stream_info->offset_count > 0)
(void) SeekBlob(image,stream_info->offsets[0]+
stream_info->segments[1],SEEK_SET);
(void) ReadDCMPixels(image,&info,stream_info,MagickFalse,exception);
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/551
CWE ID: CWE-772
Target: 1
Example 2:
Code: pch_end (void)
{
return p_end;
}
Commit Message:
CWE ID: CWE-78
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 AuthenticatorPaaskSheetModel::IsActivityIndicatorVisible() const {
return true;
}
Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break.
As requested by UX in [1], allow long host names to split a title into
two lines. This allows us to show more of the name before eliding,
although sufficiently long names will still trigger elision.
Screenshot at
https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r.
[1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12
Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34
Bug: 870892
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812
Auto-Submit: Adam Langley <[email protected]>
Commit-Queue: Nina Satragno <[email protected]>
Reviewed-by: Nina Satragno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#658114}
CWE ID: CWE-119
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: InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
InputMethodDescriptors* descriptions = new InputMethodDescriptors;
descriptions->push_back(InputMethodDescriptor(
"xkb:nl::nld", "Netherlands", "nl", "nl", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::nld", "Belgium", "be", "be", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fr::fra", "France", "fr", "fr", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::fra", "Belgium", "be", "be", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca::fra", "Canada", "ca", "ca", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de::ger", "Germany", "de", "de", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::ger", "Belgium", "be", "be", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch::ger", "Switzerland", "ch", "ch", "ger"));
descriptions->push_back(InputMethodDescriptor(
"mozc", "Mozc (US keyboard layout)", "us", "us", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-dv",
"Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja"));
descriptions->push_back(InputMethodDescriptor(
"xkb:jp::jpn", "Japan", "jp", "jp", "jpn"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru::rus", "Russia", "ru", "ru", "rus"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru:phonetic:rus",
"Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:tis820", "tis820 (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:quick", "quick (m17n)", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:telex", "telex (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:vni", "vni (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us::eng", "USA", "us", "us", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:intl:eng",
"USA - International (with dead keys)", "us(intl)", "us(intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)",
"us(altgr-intl)", "us(altgr-intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:dvorak:eng",
"USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:colemak:eng",
"USA - Colemak", "us(colemak)", "us(colemak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko"));
descriptions->push_back(InputMethodDescriptor(
"pinyin", "Pinyin", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"pinyin-dv", "Pinyin (for US Dvorak keyboard)",
"us(dvorak)", "us(dvorak)", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar"));
descriptions->push_back(InputMethodDescriptor(
"m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:br::por", "Brazil", "br", "br", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg::bul", "Bulgaria", "bg", "bg", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic",
"bg(phonetic)", "bg(phonetic)", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:cz::cze", "Czechia", "cz", "cz", "cze"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ee::est", "Estonia", "ee", "ee", "est"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es::spa", "Spain", "es", "es", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L",
"es(cat)", "es(cat)", "cat"));
descriptions->push_back(InputMethodDescriptor(
"xkb:dk::dan", "Denmark", "dk", "dk", "dan"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gr::gre", "Greece", "gr", "gr", "gre"));
descriptions->push_back(InputMethodDescriptor(
"xkb:il::heb", "Israel", "il", "il", "heb"));
descriptions->push_back(InputMethodDescriptor(
"xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible",
"kr(kr104)", "kr(kr104)", "kor"));
descriptions->push_back(InputMethodDescriptor(
"xkb:latam::spa", "Latin American", "latam", "latam", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lt::lit", "Lithuania", "lt", "lt", "lit"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant",
"lv(apostrophe)", "lv(apostrophe)", "lav"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hr::scr", "Croatia", "hr", "hr", "scr"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys",
"gb(extd)", "gb(extd)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:dvorak:eng", "United Kingdom - Dvorak",
"gb(dvorak)", "gb(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fi::fin", "Finland", "fi", "fi", "fin"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hu::hun", "Hungary", "hu", "hu", "hun"));
descriptions->push_back(InputMethodDescriptor(
"xkb:it::ita", "Italy", "it", "it", "ita"));
descriptions->push_back(InputMethodDescriptor(
"xkb:no::nob", "Norway", "no", "no", "nob"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pl::pol", "Poland", "pl", "pl", "pol"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pt::por", "Portugal", "pt", "pt", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ro::rum", "Romania", "ro", "ro", "rum"));
descriptions->push_back(InputMethodDescriptor(
"xkb:se::swe", "Sweden", "se", "se", "swe"));
descriptions->push_back(InputMethodDescriptor(
"xkb:sk::slo", "Slovakia", "sk", "sk", "slo"));
descriptions->push_back(InputMethodDescriptor(
"xkb:si::slv", "Slovenia", "si", "si", "slv"));
descriptions->push_back(InputMethodDescriptor(
"xkb:rs::srp", "Serbia", "rs", "rs", "srp"));
descriptions->push_back(InputMethodDescriptor(
"xkb:tr::tur", "Turkey", "tr", "tr", "tur"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr"));
return descriptions;
}
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: bool PassthroughResources::HasTexturesPendingDestruction() const {
return !textures_pending_destruction.empty();
}
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: HRESULT CGaiaCredentialBase::GetBaseGlsCommandline(
base::CommandLine* command_line) {
DCHECK(command_line);
base::FilePath gls_path =
chrome_launcher_support::GetChromePathForInstallationLevel(
chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION, false);
constexpr wchar_t kGlsPath[] = L"gls_path";
wchar_t custom_gls_path_value[MAX_PATH];
ULONG path_len = base::size(custom_gls_path_value);
HRESULT hr = GetGlobalFlag(kGlsPath, custom_gls_path_value, &path_len);
if (SUCCEEDED(hr)) {
base::FilePath custom_gls_path(custom_gls_path_value);
if (base::PathExists(custom_gls_path)) {
gls_path = custom_gls_path;
} else {
LOGFN(ERROR) << "Specified gls path ('" << custom_gls_path.value()
<< "') does not exist, using default gls path.";
}
}
if (gls_path.empty()) {
LOGFN(ERROR) << "No path to chrome.exe could be found.";
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
command_line->SetProgram(gls_path);
LOGFN(INFO) << "App exe: " << command_line->GetProgram().value();
command_line->AppendSwitch(kGcpwSigninSwitch);
wchar_t endpoint_url_setting[256];
ULONG endpoint_url_length = base::size(endpoint_url_setting);
if (SUCCEEDED(GetGlobalFlag(L"ep_url", endpoint_url_setting,
&endpoint_url_length)) &&
endpoint_url_setting[0]) {
GURL endpoint_url(endpoint_url_setting);
if (endpoint_url.is_valid()) {
command_line->AppendSwitchASCII(switches::kGaiaUrl,
endpoint_url.GetWithEmptyPath().spec());
command_line->AppendSwitchASCII(kGcpwEndpointPathSwitch,
endpoint_url.path().substr(1));
}
}
command_line->AppendSwitchNative("lang", GetSelectedLanguage());
return S_OK;
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284
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 ExtensionTtsController::ClearUtteranceQueue() {
while (!utterance_queue_.empty()) {
Utterance* utterance = utterance_queue_.front();
utterance_queue_.pop();
utterance->set_error(kSpeechRemovedFromQueueError);
utterance->FinishAndDestroy();
}
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::uniform3fv(
const WebGLUniformLocation* location,
const FlexibleFloat32ArrayView& v) {
WebGLRenderingContextBase::uniform3fv(location, v);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
struct kernel_lb_addr *fileset)
{
struct anchorVolDescPtr *anchor;
long main_s, main_e, reserve_s, reserve_e;
anchor = (struct anchorVolDescPtr *)bh->b_data;
/* Locate the main sequence */
main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
main_e = main_e >> sb->s_blocksize_bits;
main_e += main_s;
/* Locate the reserve sequence */
reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
reserve_e = reserve_e >> sb->s_blocksize_bits;
reserve_e += reserve_s;
/* Process the main & reserve sequences */
/* responsible for finding the PartitionDesc(s) */
if (!udf_process_sequence(sb, main_s, main_e, fileset))
return 1;
return !udf_process_sequence(sb, reserve_s, reserve_e, fileset);
}
Commit Message: udf: Avoid run away loop when partition table length is corrupted
Check provided length of partition table so that (possibly maliciously)
corrupted partition table cannot cause accessing data beyond current buffer.
Signed-off-by: Jan Kara <[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: BlockEntry::Kind Track::EOSBlock::GetKind() const
{
return kBlockEOS;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WorkerThread::stopInternal()
{
MutexLocker lock(m_threadStateMutex);
if (m_terminated)
return;
m_terminated = true;
if (m_shutdownEvent)
m_shutdownEvent->signal();
if (m_shutdown)
return;
if (!m_workerGlobalScope) {
m_terminationEvent->signal();
return;
}
terminateV8Execution();
InspectorInstrumentation::didKillAllExecutionContextTasks(m_workerGlobalScope.get());
m_debuggerMessageQueue.kill();
backingThread().postTask(FROM_HERE, new Task(threadSafeBind(&WorkerThread::shutdown, AllowCrossThreadAccess(this))));
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostViewGtk::AccessibilityScrollToPoint(
int acc_obj_id, gfx::Point point) {
if (!host_)
return;
host_->AccessibilityScrollToPoint(acc_obj_id, point);
}
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: static ssize_t lbs_debugfs_write(struct file *f, const char __user *buf,
size_t cnt, loff_t *ppos)
{
int r, i;
char *pdata;
char *p;
char *p0;
char *p1;
char *p2;
struct debug_data *d = f->private_data;
pdata = kmalloc(cnt, GFP_KERNEL);
if (pdata == NULL)
return 0;
if (copy_from_user(pdata, buf, cnt)) {
lbs_deb_debugfs("Copy from user failed\n");
kfree(pdata);
return 0;
}
p0 = pdata;
for (i = 0; i < num_of_items; i++) {
do {
p = strstr(p0, d[i].name);
if (p == NULL)
break;
p1 = strchr(p, '\n');
if (p1 == NULL)
break;
p0 = p1++;
p2 = strchr(p, '=');
if (!p2)
break;
p2++;
r = simple_strtoul(p2, NULL, 0);
if (d[i].size == 1)
*((u8 *) d[i].addr) = (u8) r;
else if (d[i].size == 2)
*((u16 *) d[i].addr) = (u16) r;
else if (d[i].size == 4)
*((u32 *) d[i].addr) = (u32) r;
else if (d[i].size == 8)
*((u64 *) d[i].addr) = (u64) r;
break;
} while (1);
}
kfree(pdata);
return (ssize_t)cnt;
}
Commit Message: libertas: potential oops in debugfs
If we do a zero size allocation then it will oops. Also we can't be
sure the user passes us a NUL terminated string so I've added a
terminator.
This code can only be triggered by root.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Acked-by: Dan Williams <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: ResourcePtr<RawResource> ResourceFetcher::fetchMainResource(FetchRequest& request, const SubstituteData& substituteData)
{
if (substituteData.isValid())
preCacheSubstituteDataForMainResource(request, substituteData);
return toRawResource(requestResource(Resource::MainResource, request));
}
Commit Message: Enforce SVG image security rules
SVG images have unique security rules that prevent them from loading
any external resources. This patch enforces these rules in
ResourceFetcher::canRequest for all non-data-uri resources. This locks
down our SVG resource handling and fixes two security bugs.
In the case of SVG images that reference other images, we had a bug
where a cached subresource would be used directly from the cache.
This has been fixed because the canRequest check occurs before we use
cached resources.
In the case of SVG images that use CSS imports, we had a bug where
imports were blindly requested. This has been fixed by stopping all
non-data-uri requests in SVG images.
With this patch we now match Gecko's behavior on both testcases.
BUG=380885, 382296
Review URL: https://codereview.chromium.org/320763002
git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CrosLibrary::TestApi::SetBrightnessLibrary(
BrightnessLibrary* library, bool own) {
library_->brightness_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: void WebGLRenderingContextBase::TexImageHelperDOMArrayBufferView(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
GLint xoffset,
GLint yoffset,
GLint zoffset,
DOMArrayBufferView* pixels,
NullDisposition null_disposition,
GLuint src_offset) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceArrayBufferView, target,
level, internalformat, width, height, depth, border,
format, type, xoffset, yoffset, zoffset))
return;
TexImageDimension source_type;
if (function_id == kTexImage2D || function_id == kTexSubImage2D)
source_type = kTex2D;
else
source_type = kTex3D;
if (!ValidateTexFuncData(func_name, source_type, level, width, height, depth,
format, type, pixels, null_disposition, src_offset))
return;
uint8_t* data = reinterpret_cast<uint8_t*>(
pixels ? pixels->BaseAddressMaybeShared() : nullptr);
if (src_offset) {
DCHECK(pixels);
data += src_offset * pixels->TypeSize();
}
Vector<uint8_t> temp_data;
bool change_unpack_alignment = false;
if (data && (unpack_flip_y_ || unpack_premultiply_alpha_)) {
if (source_type == kTex2D) {
if (!WebGLImageConversion::ExtractTextureData(
width, height, format, type, unpack_alignment_, unpack_flip_y_,
unpack_premultiply_alpha_, data, temp_data)) {
SynthesizeGLError(GL_INVALID_OPERATION, func_name,
"Invalid format/type combination.");
return;
}
data = temp_data.data();
}
change_unpack_alignment = true;
}
ContextGL()->TexImage3D(target, level,
ConvertTexInternalFormat(internalformat, type),
width, height, depth, border, format, type, data);
return;
}
if (function_id == kTexSubImage3D) {
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width,
height, depth, format, type, data);
return;
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(
this, change_unpack_alignment);
if (function_id == kTexImage2D)
TexImage2DBase(target, level, internalformat, width, height, border, format,
type, data);
else if (function_id == kTexSubImage2D)
ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height,
format, type, data);
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125
Target: 1
Example 2:
Code: tty_ldisc_lock_pair_timeout(struct tty_struct *tty, struct tty_struct *tty2,
unsigned long timeout)
{
int ret;
if (tty < tty2) {
ret = __tty_ldisc_lock(tty, timeout);
if (ret) {
ret = __tty_ldisc_lock_nested(tty2, timeout);
if (!ret)
__tty_ldisc_unlock(tty);
}
} else {
/* if this is possible, it has lots of implications */
WARN_ON_ONCE(tty == tty2);
if (tty2 && tty != tty2) {
ret = __tty_ldisc_lock(tty2, timeout);
if (ret) {
ret = __tty_ldisc_lock_nested(tty, timeout);
if (!ret)
__tty_ldisc_unlock(tty2);
}
} else
ret = __tty_ldisc_lock(tty, timeout);
}
if (!ret)
return -EBUSY;
set_bit(TTY_LDISC_HALTED, &tty->flags);
if (tty2)
set_bit(TTY_LDISC_HALTED, &tty2->flags);
return 0;
}
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: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
}
Commit Message: xkbcomp: Don't explode on invalid virtual modifiers
testcase: 'virtualModifiers=LevelThreC'
Signed-off-by: Daniel Stone <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread,
wgint restval, ccon *con, int count, wgint *last_expected_bytes,
FILE *warc_tmp)
{
int csock, dtsock, local_sock, res;
uerr_t err = RETROK; /* appease the compiler */
FILE *fp;
char *respline, *tms;
const char *user, *passwd, *tmrate;
int cmd = con->cmd;
bool pasv_mode_open = false;
wgint expected_bytes = 0;
bool got_expected_bytes = false;
bool rest_failed = false;
bool rest_failed = false;
int flags;
wgint rd_size, previous_rd_size = 0;
char type_char;
bool try_again;
bool list_a_used = false;
assert (con != NULL);
assert (con->target != NULL);
/* Debug-check of the sanity of the request by making sure that LIST
and RETR are never both requested (since we can handle only one
at a time. */
assert (!((cmd & DO_LIST) && (cmd & DO_RETR)));
/* Make sure that at least *something* is requested. */
assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0);
*qtyread = restval;
user = u->user;
passwd = u->passwd;
search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1);
user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user);
if (!user) user = "anonymous";
passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd);
if (!passwd) passwd = "-wget@";
dtsock = -1;
local_sock = -1;
con->dltime = 0;
if (!(cmd & DO_LOGIN))
csock = con->csock;
else /* cmd & DO_LOGIN */
{
char *host = con->proxy ? con->proxy->host : u->host;
int port = con->proxy ? con->proxy->port : u->port;
/* Login to the server: */
/* First: Establish the control connection. */
csock = connect_to_host (host, port);
if (csock == E_HOST)
return HOSTERR;
else if (csock < 0)
return (retryable_socket_connect_error (errno)
? CONERROR : CONIMPOSSIBLE);
if (cmd & LEAVE_PENDING)
con->csock = csock;
else
con->csock = -1;
/* Second: Login with proper USER/PASS sequence. */
logprintf (LOG_VERBOSE, _("Logging in as %s ... "),
quotearg_style (escape_quoting_style, user));
if (opt.server_response)
logputs (LOG_ALWAYS, "\n");
if (con->proxy)
{
/* If proxy is in use, log in as username@target-site. */
char *logname = concat_strings (user, "@", u->host, (char *) 0);
err = ftp_login (csock, logname, passwd);
xfree (logname);
}
else
err = ftp_login (csock, user, passwd);
/* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Error in server greeting.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPLOGREFUSED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("The server refuses login.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGREFUSED;
case FTPLOGINC:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Login incorrect.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGINC;
case FTPOK:
if (!opt.server_response)
logputs (LOG_VERBOSE, _("Logged in!\n"));
break;
default:
abort ();
}
/* Third: Get the system type */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SYST ... ");
err = ftp_syst (csock, &con->rs, &con->rsu);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Server error, can't determine system type.\n"));
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response && err != FTPSRVERR)
logputs (LOG_VERBOSE, _("done. "));
/* 2013-10-17 Andrea Urbani (matfanjol)
According to the system type I choose which
list command will be used.
If I don't know that system, I will try, the
first time of each session, "LIST -a" and
"LIST". (see __LIST_A_EXPLANATION__ below) */
switch (con->rs)
{
case ST_VMS:
/* About ST_VMS there is an old note:
2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not
fail, but will never do what is desired here,
skip directly to the simple "LIST" command
(assumed to be the last one in the list). */
DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
break;
case ST_UNIX:
if (con->rsu == UST_MULTINET)
{
DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
}
else if (con->rsu == UST_TYPE_L8)
{
DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST;
}
break;
default:
break;
}
/* Fourth: Find the initial ftp directory */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> PWD ... ");
err = ftp_pwd (csock, &con->id);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR :
/* PWD unsupported -- assume "/". */
xfree (con->id);
con->id = xstrdup ("/");
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise move.
This code was disabled but left in as an example of what not
to do.
*/
/* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]".
Convert it to "/INITIAL/FOLDER" */
if (con->rs == ST_VMS)
{
char *path = strchr (con->id, '[');
char *pathend = path ? strchr (path + 1, ']') : NULL;
if (!path || !pathend)
DEBUGP (("Initial VMS directory not in the form [...]!\n"));
else
{
char *idir = con->id;
DEBUGP (("Preprocessing the initial VMS directory\n"));
DEBUGP ((" old = '%s'\n", con->id));
/* We do the conversion in-place by copying the stuff
between [ and ] to the beginning, and changing dots
to slashes at the same time. */
*idir++ = '/';
for (++path; path < pathend; path++, idir++)
*idir = *path == '.' ? '/' : *path;
*idir = '\0';
DEBUGP ((" new = '%s'\n\n", con->id));
}
}
#endif /* 0 */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
/* Fifth: Set the FTP type. */
type_char = ftp_process_type (u->params);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char);
err = ftp_type (csock, type_char);
/* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPUNKNOWNTYPE:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET,
_("Unknown type `%c', closing control connection.\n"),
type_char);
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* do login */
if (cmd & DO_CWD)
{
if (!*u->dir)
logputs (LOG_VERBOSE, _("==> CWD not needed.\n"));
else
{
const char *targ = NULL;
int cwd_count;
int cwd_end;
int cwd_start;
char *target = u->dir;
DEBUGP (("changing working directory\n"));
/* Change working directory. To change to a non-absolute
Unix directory, we need to prepend initial directory
(con->id) to it. Absolute directories "just work".
A relative directory is one that does not begin with '/'
and, on non-Unix OS'es, one that doesn't begin with
"[a-z]:".
This is not done for OS400, which doesn't use
"/"-delimited directories, nor does it support directory
hierarchies. "CWD foo" followed by "CWD bar" leaves us
in "bar", not in "foo/bar", as would be customary
elsewhere. */
/* 2004-09-20 SMS.
Why is this wise even on UNIX? It certainly fouls VMS.
See below for a more reliable, more universal method.
*/
/* 2008-04-22 MJC.
I'm not crazy about it either. I'm informed it's useful
for misconfigured servers that have some dirs in the path
with +x but -r, but this method is not RFC-conformant. I
understand the need to deal with crappy server
configurations, but it's far better to use the canonical
method first, and fall back to kludges second.
*/
if (target[0] != '/'
&& !(con->rs != ST_UNIX
&& c_isalpha (target[0])
&& target[1] == ':')
&& (con->rs != ST_OS400)
&& (con->rs != ST_VMS))
{
int idlen = strlen (con->id);
char *ntarget, *p;
/* Strip trailing slash(es) from con->id. */
while (idlen > 0 && con->id[idlen - 1] == '/')
--idlen;
p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1);
memcpy (p, con->id, idlen);
p += idlen;
*p++ = '/';
strcpy (p, target);
DEBUGP (("Prepended initial PWD to relative path:\n"));
DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n",
con->id, target, ntarget));
target = ntarget;
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise
move.
This code was disabled but left in as an example of what
not to do.
*/
/* If the FTP host runs VMS, we will have to convert the absolute
directory path in UNIX notation to absolute directory path in
VMS notation as VMS FTP servers do not like UNIX notation of
absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */
if (con->rs == ST_VMS)
{
char *tmpp;
char *ntarget = (char *)alloca (strlen (target) + 2);
/* We use a converted initial dir, so directories in
TARGET will be separated with slashes, something like
"/INITIAL/FOLDER/DIR/SUBDIR". Convert that to
"[INITIAL.FOLDER.DIR.SUBDIR]". */
strcpy (ntarget, target);
assert (*ntarget == '/');
*ntarget = '[';
for (tmpp = ntarget + 1; *tmpp; tmpp++)
if (*tmpp == '/')
*tmpp = '.';
*tmpp++ = ']';
*tmpp = '\0';
DEBUGP (("Changed file name to VMS syntax:\n"));
DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget));
target = ntarget;
}
#endif /* 0 */
/* 2004-09-20 SMS.
A relative directory is relative to the initial directory.
Thus, what _is_ useful on VMS (and probably elsewhere) is
to CWD to the initial directory (ideally, whatever the
server reports, _exactly_, NOT badly UNIX-ixed), and then
CWD to the (new) relative directory. This should probably
be restructured as a function, called once or twice, but
I'm lazy enough to take the badly indented loop short-cut
for now.
*/
/* Decide on one pass (absolute) or two (relative).
The VMS restriction may be relaxed when the squirrely code
above is reformed.
*/
if ((con->rs == ST_VMS) && (target[0] != '/'))
{
cwd_start = 0;
DEBUGP (("Using two-step CWD for relative path.\n"));
}
else
{
/* Go straight to the target. */
cwd_start = 1;
}
/* At least one VMS FTP server (TCPware V5.6-2) can switch to
a UNIX emulation mode when given a UNIX-like directory
specification (like "a/b/c"). If allowed to continue this
way, LIST interpretation will be confused, because the
system type (SYST response) will not be re-checked, and
future UNIX-format directory listings (for multiple URLs or
"-r") will be horribly misinterpreted.
The cheap and nasty work-around is to do a "CWD []" after a
UNIX-like directory specification is used. (A single-level
directory is harmless.) This puts the TCPware server back
into VMS mode, and does no harm on other servers.
Unlike the rest of this block, this particular behavior
_is_ VMS-specific, so it gets its own VMS test.
*/
if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL))
{
cwd_end = 3;
DEBUGP (("Using extra \"CWD []\" step for VMS server.\n"));
}
else
{
cwd_end = 2;
}
/* 2004-09-20 SMS. */
/* Sorry about the deviant indenting. Laziness. */
for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++)
{
switch (cwd_count)
{
case 0:
/* Step one (optional): Go to the initial directory,
exactly as reported by the server.
*/
targ = con->id;
break;
case 1:
/* Step two: Go to the target directory. (Absolute or
relative will work now.)
*/
targ = target;
break;
case 2:
/* Step three (optional): "CWD []" to restore server
VMS-ness.
*/
targ = "[]";
break;
default:
logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()"));
logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"),
cwd_count, cwd_start, cwd_end);
abort ();
}
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count,
quotearg_style (escape_quoting_style, target));
err = ftp_cwd (csock, targ);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"),
quote (u->dir));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
} /* for */
/* 2004-09-20 SMS. */
} /* else */
}
else /* do not CWD */
logputs (LOG_VERBOSE, _("==> CWD not required.\n"));
if ((cmd & DO_RETR) && passed_expected_bytes == 0)
{
if (opt.verbose)
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SIZE %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
err = ftp_size (csock, u->file, &expected_bytes);
/* FTPRERR */
switch (err)
{
case FTPRERR:
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
got_expected_bytes = true;
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
{
logprintf (LOG_VERBOSE, "%s\n",
expected_bytes ?
number_to_static_string (expected_bytes) :
_("done.\n"));
}
}
if (cmd & DO_RETR && restval > 0 && restval == expected_bytes)
{
/* Server confirms that file has length restval. We should stop now.
Some servers (f.e. NcFTPd) return error when receive REST 0 */
logputs (LOG_VERBOSE, _("File has already been retrieved.\n"));
fd_close (csock);
con->csock = -1;
return RETRFINISHED;
}
do
{
try_again = false;
/* If anything is to be retrieved, PORT (or PASV) must be sent. */
if (cmd & (DO_LIST | DO_RETR))
{
if (opt.ftp_pasv)
{
ip_address passive_addr;
int passive_port;
err = ftp_do_pasv (csock, &passive_addr, &passive_port);
/* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNOPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n"));
break;
case FTPINVPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n"));
break;
case FTPOK:
break;
default:
abort ();
} /* switch (err) */
if (err==FTPOK)
{
DEBUGP (("trying to connect to %s port %d\n",
print_address (&passive_addr), passive_port));
dtsock = connect_to_ip (&passive_addr, passive_port, NULL);
if (dtsock < 0)
{
int save_errno = errno;
fd_close (csock);
con->csock = -1;
logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"),
print_address (&passive_addr), passive_port,
strerror (save_errno));
? CONERROR : CONIMPOSSIBLE);
}
pasv_mode_open = true; /* Flag to avoid accept port */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* err==FTP_OK */
}
if (!pasv_mode_open) /* Try to use a port command if PASV failed */
{
err = ftp_do_port (csock, &local_sock);
/* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR,
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case CONSOCKERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPSYSERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"),
strerror (errno));
fd_close (dtsock);
return err;
case FTPPORTERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Invalid PORT.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
} /* port switch */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* dtsock == -1 */
} /* cmd & (DO_LIST | DO_RETR) */
/* Restart if needed. */
if (restval && (cmd & DO_RETR))
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> REST %s ... ",
number_to_static_string (restval));
err = ftp_rest (csock, restval);
/* FTPRERR, WRITEFAILED, FTPRESTFAIL */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPRESTFAIL:
logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n"));
rest_failed = true;
break;
case FTPOK:
break;
default:
abort ();
}
if (err != FTPRESTFAIL && !opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* restval && cmd & DO_RETR */
if (cmd & DO_RETR)
{
/* If we're in spider mode, don't really retrieve anything except
the directory listing and verify whether the given "file" exists. */
if (opt.spider)
{
bool exists = false;
struct fileinfo *f;
uerr_t _res = ftp_get_listing (u, con, &f);
/* Set the DO_RETR command flag again, because it gets unset when
calling ftp_get_listing() and would otherwise cause an assertion
failure earlier on when this function gets repeatedly called
(e.g., when recursing). */
con->cmd |= DO_RETR;
if (_res == RETROK)
{
while (f)
{
if (!strcmp (f->name, u->file))
{
exists = true;
break;
}
f = f->next;
}
if (exists)
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("File %s exists.\n"),
quote (u->file));
}
else
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n"),
quote (u->file));
}
}
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return RETRFINISHED;
}
if (opt.verbose)
{
if (!opt.server_response)
{
if (restval)
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_VERBOSE, "==> RETR %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
}
err = ftp_retr (csock, u->file);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"),
quote (u->file));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* do retrieve */
if (cmd & DO_LIST)
{
if (!opt.server_response)
logputs (LOG_VERBOSE, "==> LIST ... ");
/* As Maciej W. Rozycki ([email protected]) says, `LIST'
without arguments is better than `LIST .'; confirmed by
RFC959. */
err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used);
/* FTPRERR, WRITEFAILED */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"),
quote ("."));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* cmd & DO_LIST */
if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST)))
return RETRFINISHED;
/* Some FTP servers return the total length of file after REST
command, others just return the remaining size. */
if (passed_expected_bytes && restval && expected_bytes
&& (expected_bytes == passed_expected_bytes - restval))
{
DEBUGP (("Lying FTP server found, adjusting.\n"));
expected_bytes = passed_expected_bytes;
}
/* If no transmission was required, then everything is OK. */
if (!pasv_mode_open) /* we are not using pasive mode so we need
to accept */
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: query_has_required_values(QUERYTYPE *query)
{
if (query->size <= 0)
return false;
return contains_required_value(GETQUERY(query) + query->size - 1);
}
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 ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels = 0, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
if (numChannels < chansSpecified || numChannels < 1 || numChannels > 256) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
if (!config->num_channels) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
Commit Message: issue #67: make sure sample rate is specified and non-zero in DFF files
CWE ID: CWE-824
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 CSSStyleSheet::CanAccessRules() const {
if (enable_rule_access_for_inspector_)
return true;
if (is_inline_stylesheet_)
return true;
KURL base_url = contents_->BaseURL();
if (base_url.IsEmpty())
return true;
Document* document = OwnerDocument();
if (!document)
return true;
if (document->GetSecurityOrigin()->CanReadContent(base_url))
return true;
if (allow_rule_access_from_origin_ &&
document->GetSecurityOrigin()->CanAccess(
allow_rule_access_from_origin_.get())) {
return true;
}
return false;
}
Commit Message: Disallow access to opaque CSS responses.
Bug: 848786
Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec
Reviewed-on: https://chromium-review.googlesource.com/1088335
Reviewed-by: Kouhei Ueno <[email protected]>
Commit-Queue: Matt Falkenhagen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565537}
CWE ID: CWE-200
Target: 1
Example 2:
Code: PositionWithAffinity RenderBlock::positionForPoint(const LayoutPoint& point)
{
if (isTable())
return RenderBox::positionForPoint(point);
if (isReplaced()) {
LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
if (pointLogicalLeft < 0)
return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
if (pointLogicalLeft >= logicalWidth())
return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
if (pointLogicalTop < 0)
return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
if (pointLogicalTop >= logicalHeight())
return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
}
LayoutPoint pointInContents = point;
offsetForContents(pointInContents);
LayoutPoint pointInLogicalContents(pointInContents);
if (!isHorizontalWritingMode())
pointInLogicalContents = pointInLogicalContents.transposedPoint();
if (childrenInline())
return positionForPointWithInlineChildren(pointInLogicalContents);
RenderBox* lastCandidateBox = lastChildBox();
while (lastCandidateBox && !isChildHitTestCandidate(lastCandidateBox))
lastCandidateBox = lastCandidateBox->previousSiblingBox();
bool blocksAreFlipped = style()->isFlippedBlocksWritingMode();
if (lastCandidateBox) {
if (pointInLogicalContents.y() > logicalTopForChild(lastCandidateBox)
|| (!blocksAreFlipped && pointInLogicalContents.y() == logicalTopForChild(lastCandidateBox)))
return positionForPointRespectingEditingBoundaries(this, lastCandidateBox, pointInContents);
for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
if (!isChildHitTestCandidate(childBox))
continue;
LayoutUnit childLogicalBottom = logicalTopForChild(childBox) + logicalHeightForChild(childBox);
if (isChildHitTestCandidate(childBox) && (pointInLogicalContents.y() < childLogicalBottom
|| (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
}
}
return RenderBox::positionForPoint(point);
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pud_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
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: void BackgroundLoaderOffliner::StartSnapshot() {
if (!pending_request_.get()) {
DVLOG(1) << "Pending request was cleared during delay.";
return;
}
DCHECK(is_low_bar_met_)
<< "Minimum quality must have been reached before saving a snapshot";
AddLoadingSignal("Snapshotting");
SavePageRequest request(*pending_request_.get());
if (page_load_state_ != SUCCESS) {
Offliner::RequestStatus status;
switch (page_load_state_) {
case RETRIABLE_NET_ERROR:
status = Offliner::RequestStatus::LOADING_FAILED_NET_ERROR;
break;
case RETRIABLE_HTTP_ERROR:
status = Offliner::RequestStatus::LOADING_FAILED_HTTP_ERROR;
break;
case NONRETRIABLE:
status = Offliner::RequestStatus::LOADING_FAILED_NO_RETRY;
break;
default:
NOTREACHED();
status = Offliner::RequestStatus::LOADING_FAILED;
}
std::move(completion_callback_).Run(request, status);
ResetState();
return;
}
content::WebContents* web_contents(
content::WebContentsObserver::web_contents());
Offliner::RequestStatus loaded_page_error =
CanSavePageInBackground(web_contents);
if (loaded_page_error != Offliner::RequestStatus::UNKNOWN) {
std::move(completion_callback_).Run(request, loaded_page_error);
ResetState();
return;
}
save_state_ = SAVING;
RequestStats& image_stats = stats_[ResourceDataType::IMAGE];
RequestStats& css_stats = stats_[ResourceDataType::TEXT_CSS];
RequestStats& xhr_stats = stats_[ResourceDataType::XHR];
bool image_complete = (image_stats.requested == image_stats.completed);
bool css_complete = (css_stats.requested == css_stats.completed);
bool xhr_complete = (xhr_stats.requested == xhr_stats.completed);
RecordResourceCompletionUMA(image_complete, css_complete, xhr_complete);
if (IsOfflinePagesLoadSignalCollectingEnabled()) {
signal_data_.SetDouble("StartedImages", image_stats.requested);
signal_data_.SetDouble("CompletedImages", image_stats.completed);
signal_data_.SetDouble("StartedCSS", css_stats.requested);
signal_data_.SetDouble("CompletedCSS", css_stats.completed);
signal_data_.SetDouble("StartedXHR", xhr_stats.requested);
signal_data_.SetDouble("CompletedXHR", xhr_stats.completed);
std::string headers = base::StringPrintf(
"%s\r\n%s\r\n\r\n", kContentTransferEncodingBinary, kXHeaderForSignals);
std::string body;
base::JSONWriter::Write(signal_data_, &body);
std::string content_type = kContentType;
std::string content_location = base::StringPrintf(
"cid:signal-data-%" PRId64 "@mhtml.blink", request.request_id());
content::MHTMLExtraParts* extra_parts =
content::MHTMLExtraParts::FromWebContents(web_contents);
DCHECK(extra_parts);
if (extra_parts != nullptr) {
extra_parts->AddExtraMHTMLPart(content_type, content_location, headers,
body);
}
}
std::unique_ptr<OfflinePageArchiver> archiver(new OfflinePageMHTMLArchiver());
OfflinePageModel::SavePageParams params;
params.url = web_contents->GetLastCommittedURL();
params.client_id = request.client_id();
params.proposed_offline_id = request.request_id();
params.is_background = true;
params.use_page_problem_detectors = true;
params.request_origin = request.request_origin();
if (!request.original_url().is_empty())
params.original_url = request.original_url();
else if (params.url != request.url())
params.original_url = request.url();
offline_page_model_->SavePage(
params, std::move(archiver), web_contents,
base::Bind(&BackgroundLoaderOffliner::OnPageSaved,
weak_ptr_factory_.GetWeakPtr()));
}
Commit Message: Remove unused histograms from the background loader offliner.
Bug: 975512
Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361
Reviewed-by: Cathy Li <[email protected]>
Reviewed-by: Steven Holte <[email protected]>
Commit-Queue: Peter Williamson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#675332}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int index_entry_isrch_path(const void *path, const void *array_member)
{
const git_index_entry *entry = array_member;
return strcasecmp((const char *)path, entry->path);
}
Commit Message: index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: dump_threads(void)
{
FILE *fp;
char time_buf[26];
element e;
vrrp_t *vrrp;
char *file_name;
file_name = make_file_name("/tmp/thread_dump.dat",
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
fp = fopen(file_name, "a");
FREE(file_name);
set_time_now();
ctime_r(&time_now.tv_sec, time_buf);
fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec);
dump_thread_data(master, fp);
fprintf(fp, "alloc = %lu\n", master->alloc);
fprintf(fp, "\n");
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
ctime_r(&vrrp->sands.tv_sec, time_buf);
fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec,
vrrp->state == VRRP_STATE_INIT ? "INIT" :
vrrp->state == VRRP_STATE_BACK ? "BACKUP" :
vrrp->state == VRRP_STATE_MAST ? "MASTER" :
vrrp->state == VRRP_STATE_FAULT ? "FAULT" :
vrrp->state == VRRP_STATE_STOP ? "STOP" :
vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown");
}
fclose(fp);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
int ulen;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
ulen = xfrm_replay_state_esn_len(up);
if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen)
return -EINVAL;
return 0;
}
Commit Message: xfrm_user: validate XFRM_MSG_NEWAE XFRMA_REPLAY_ESN_VAL replay_window
When a new xfrm state is created during an XFRM_MSG_NEWSA call we
validate the user supplied replay_esn to ensure that the size is valid
and to ensure that the replay_window size is within the allocated
buffer. However later it is possible to update this replay_esn via a
XFRM_MSG_NEWAE call. There we again validate the size of the supplied
buffer matches the existing state and if so inject the contents. We do
not at this point check that the replay_window is within the allocated
memory. This leads to out-of-bounds reads and writes triggered by
netlink packets. This leads to memory corruption and the potential for
priviledge escalation.
We already attempt to validate the incoming replay information in
xfrm_new_ae() via xfrm_replay_verify_len(). This confirms that the user
is not trying to change the size of the replay state buffer which
includes the replay_esn. It however does not check the replay_window
remains within that buffer. Add validation of the contained
replay_window.
CVE-2017-7184
Signed-off-by: Andy Whitcroft <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static int enter_vmx_operation(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs *shadow_vmcs;
if (cpu_has_vmx_msr_bitmap()) {
vmx->nested.msr_bitmap =
(unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx->nested.msr_bitmap)
goto out_msr_bitmap;
}
vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
if (!vmx->nested.cached_vmcs12)
goto out_cached_vmcs12;
if (enable_shadow_vmcs) {
shadow_vmcs = alloc_vmcs();
if (!shadow_vmcs)
goto out_shadow_vmcs;
/* mark vmcs as shadow */
shadow_vmcs->revision_id |= (1u << 31);
/* init shadow vmcs */
vmcs_clear(shadow_vmcs);
vmx->vmcs01.shadow_vmcs = shadow_vmcs;
}
INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num = 0;
hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL_PINNED);
vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
vmx->nested.vmxon = true;
return 0;
out_shadow_vmcs:
kfree(vmx->nested.cached_vmcs12);
out_cached_vmcs12:
free_page((unsigned long)vmx->nested.msr_bitmap);
out_msr_bitmap:
return -ENOMEM;
}
Commit Message: kvm: nVMX: Don't allow L2 to access the hardware CR8
If L1 does not specify the "use TPR shadow" VM-execution control in
vmcs12, then L0 must specify the "CR8-load exiting" and "CR8-store
exiting" VM-execution controls in vmcs02. Failure to do so will give
the L2 VM unrestricted read/write access to the hardware CR8.
This fixes CVE-2017-12154.
Signed-off-by: Jim Mattson <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Paolo Bonzini <[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 RECORD_LAYER_clear(RECORD_LAYER *rl)
{
rl->rstate = SSL_ST_READ_HEADER;
/*
* Do I need to clear read_ahead? As far as I can tell read_ahead did not
* previously get reset by SSL_clear...so I'll keep it that way..but is
* that right?
*/
rl->packet = NULL;
rl->packet_length = 0;
rl->wnum = 0;
memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
rl->alert_fragment_len = 0;
memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
rl->handshake_fragment_len = 0;
rl->wpend_tot = 0;
rl->wpend_type = 0;
rl->wpend_ret = 0;
rl->wpend_buf = NULL;
SSL3_BUFFER_clear(&rl->rbuf);
ssl3_release_write_buffer(rl->s);
rl->numrpipes = 0;
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
RECORD_LAYER_reset_read_sequence(rl);
RECORD_LAYER_reset_write_sequence(rl);
if (rl->d)
DTLS_RECORD_LAYER_clear(rl);
}
Commit Message: Don't change the state of the ETM flags until CCS processing
Changing the ciphersuite during a renegotiation can result in a crash
leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS
so this is TLS only.
The problem is caused by changing the flag indicating whether to use ETM
or not immediately on negotiation of ETM, rather than at CCS. Therefore,
during a renegotiation, if the ETM state is changing (usually due to a
change of ciphersuite), then an error/crash will occur.
Due to the fact that there are separate CCS messages for read and write
we actually now need two flags to determine whether to use ETM or not.
CVE-2017-3733
Reviewed-by: Richard Levitte <[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: SegmentInfo::~SegmentInfo()
{
delete[] m_pMuxingAppAsUTF8;
m_pMuxingAppAsUTF8 = NULL;
delete[] m_pWritingAppAsUTF8;
m_pWritingAppAsUTF8 = NULL;
delete[] m_pTitleAsUTF8;
m_pTitleAsUTF8 = NULL;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: void testUriUserInfoHostPort3() {
UriParserStateA stateA;
UriUriA uriA;
stateA.uri = &uriA;
const char * const input = "http" "://" "abcdefg" "@" "localhost";
TEST_ASSERT(0 == uriParseUriA(&stateA, input));
TEST_ASSERT(uriA.userInfo.first == input + 4 + 3);
TEST_ASSERT(uriA.userInfo.afterLast == input + 4 + 3 + 7);
TEST_ASSERT(uriA.hostText.first == input + 4 + 3 + 7 + 1);
TEST_ASSERT(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9);
TEST_ASSERT(uriA.portText.first == NULL);
TEST_ASSERT(uriA.portText.afterLast == NULL);
uriFreeUriMembersA(&uriA);
}
Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team
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: int btsock_thread_exit(int h)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created");
return FALSE;
}
sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0};
if(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd))
{
pthread_join(ts[h].thread_id, 0);
pthread_mutex_lock(&thread_slot_lock);
free_thread_slot(h);
pthread_mutex_unlock(&thread_slot_lock);
return TRUE;
}
return FALSE;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
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 vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
}
Commit Message: kvm:vmx: more complete state update on APICv on/off
The function to update APICv on/off state (in particular, to deactivate
it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust
APICv-related fields among secondary processor-based VM-execution
controls. As a result, Windows 2012 guests get stuck when SynIC-based
auto-EOI interrupt intersected with e.g. an IPI in the guest.
In addition, the MSR intercept bitmap isn't updated every time "virtualize
x2APIC mode" is toggled. This path can only be triggered by a malicious
guest, because Windows didn't use x2APIC but rather their own synthetic
APIC access MSRs; however a guest running in a SynIC-enabled VM could
switch to x2APIC and thus obtain direct access to host APIC MSRs
(CVE-2016-4440).
The patch fixes those omissions.
Signed-off-by: Roman Kagan <[email protected]>
Reported-by: Steve Rutherford <[email protected]>
Reported-by: Yang Zhang <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: ServiceWorkerContainer::ServiceWorkerContainer(ExecutionContext* executionContext)
: ContextLifecycleObserver(executionContext)
, m_provider(0)
{
if (!executionContext)
return;
if (ServiceWorkerContainerClient* client = ServiceWorkerContainerClient::from(executionContext)) {
m_provider = client->provider();
if (m_provider)
m_provider->setClient(this);
}
}
Commit Message: Check CSP before registering ServiceWorkers
Service Worker registrations should be subject to the same CSP checks as
other workers. The spec doesn't say this explicitly
(https://www.w3.org/TR/CSP2/#directive-child-src-workers says "Worker or
SharedWorker constructors"), but it seems to be in the spirit of things,
and it matches Firefox's behavior.
BUG=579801
Review URL: https://codereview.chromium.org/1861253004
Cr-Commit-Position: refs/heads/master@{#385775}
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: SecureProxyChecker::SecureProxyChecker(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: url_loader_factory_(std::move(url_loader_factory)) {}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
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: HeadlessWebContentsImpl::HeadlessWebContentsImpl(
content::WebContents* web_contents,
HeadlessBrowserContextImpl* browser_context)
: content::WebContentsObserver(web_contents),
web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)),
web_contents_(web_contents),
agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)),
inject_mojo_services_into_isolated_world_(false),
browser_context_(browser_context),
render_process_host_(web_contents->GetMainFrame()->GetProcess()),
weak_ptr_factory_(this) {
#if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
HeadlessPrintManager::CreateForWebContents(web_contents);
//// TODO(weili): Add support for printing OOPIFs.
#endif
web_contents->GetMutableRendererPrefs()->accept_languages =
browser_context->options()->accept_language();
web_contents_->SetDelegate(web_contents_delegate_.get());
render_process_host_->AddObserver(this);
agent_host_->AddObserver(this);
}
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: void FeatureInfo::InitializeBasicState(const base::CommandLine* command_line) {
if (!command_line)
return;
feature_flags_.enable_shader_name_hashing =
!command_line->HasSwitch(switches::kDisableShaderNameHashing);
feature_flags_.is_swiftshader_for_webgl =
(command_line->GetSwitchValueASCII(switches::kUseGL) ==
gl::kGLImplementationSwiftShaderForWebGLName);
feature_flags_.is_swiftshader =
(command_line->GetSwitchValueASCII(switches::kUseGL) ==
gl::kGLImplementationSwiftShaderName);
disable_shader_translator_ =
command_line->HasSwitch(switches::kDisableGLSLTranslator);
}
Commit Message: gpu: Disallow use of IOSurfaces for half-float format with swiftshader.
[email protected]
Bug: 998038
Change-Id: Ic31d28938ef205b36657fc7bd297fe8a63d08543
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1798052
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#695826}
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CustomButton::SetAnimationDuration(int duration) {
hover_animation_->SetSlideDuration(duration);
}
Commit Message: Custom buttons should only handle accelerators when focused.
BUG=541415
Review URL: https://codereview.chromium.org/1437523005
Cr-Commit-Position: refs/heads/master@{#360130}
CWE ID: CWE-254
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 DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier,
const string16& database_name,
const string16& description,
int64 estimated_size) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
int64 database_size = 0;
db_tracker_->DatabaseOpened(origin_identifier, database_name, description,
estimated_size, &database_size);
database_connections_.AddConnection(origin_identifier, database_name);
Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name,
database_size));
}
Commit Message: WebDatabase: check path traversal in origin_identifier
BUG=172264
Review URL: https://chromiumcodereview.appspot.com/12212091
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-22
Target: 1
Example 2:
Code: static int tipc_nl_compat_media_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct nlattr *media[TIPC_NLA_MEDIA_MAX + 1];
int err;
if (!attrs[TIPC_NLA_MEDIA])
return -EINVAL;
err = nla_parse_nested(media, TIPC_NLA_MEDIA_MAX, attrs[TIPC_NLA_MEDIA],
NULL);
if (err)
return err;
return tipc_add_tlv(msg->rep, TIPC_TLV_MEDIA_NAME,
nla_data(media[TIPC_NLA_MEDIA_NAME]),
nla_len(media[TIPC_NLA_MEDIA_NAME]));
}
Commit Message: tipc: fix an infoleak in tipc_nl_compat_link_dump
link_info.str is a char array of size 60. Memory after the NULL
byte is not initialized. Sending the whole object out can cause
a leak.
Signed-off-by: Kangjie Lu <[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: static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
{
if (ssh->queueing)
ssh2_pkt_queue(ssh, pkt);
else
ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void EglRenderingVDAClient::CreateDecoder() {
CHECK(decoder_deleted());
#if defined(OS_WIN)
scoped_refptr<DXVAVideoDecodeAccelerator> decoder =
new DXVAVideoDecodeAccelerator(this, base::GetCurrentProcessHandle());
#else // OS_WIN
scoped_refptr<OmxVideoDecodeAccelerator> decoder =
new OmxVideoDecodeAccelerator(this);
decoder->SetEglState(egl_display(), egl_context());
#endif // OS_WIN
decoder_ = decoder.release();
SetState(CS_DECODER_SET);
if (decoder_deleted())
return;
media::VideoCodecProfile profile = media::H264PROFILE_BASELINE;
if (profile_ != -1)
profile = static_cast<media::VideoCodecProfile>(profile_);
CHECK(decoder_->Initialize(profile));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static void ByteStringAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "byteStringAttribute");
V8StringResource<> cpp_value = NativeValueTraits<IDLByteString>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
impl->setByteStringAttribute(cpp_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: void IndexedDBTransaction::AddPendingObserver(
int32_t observer_id,
const IndexedDBObserver::Options& options) {
DCHECK_NE(mode(), blink::kWebIDBTransactionModeVersionChange);
pending_observers_.push_back(std::make_unique<IndexedDBObserver>(
observer_id, object_store_ids_, options));
}
Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose
Patch is as small as possible for merging.
Bug: 842990
Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f
Reviewed-on: https://chromium-review.googlesource.com/1062935
Commit-Queue: Daniel Murphy <[email protected]>
Commit-Queue: Victor Costan <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#559383}
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: SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle,
SQLSMALLINT rec_number,
SQLSMALLINT field_identifier,
SQLPOINTER value,
SQLINTEGER buffer_length )
{
/*
* not quite sure how the descriptor can be
* allocated to a statement, all the documentation talks
* about state transitions on statement states, but the
* descriptor may be allocated with more than one statement
* at one time. Which one should I check ?
*/
DMHDESC descriptor = (DMHDESC) descriptor_handle;
SQLRETURN ret;
SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ];
int isStrField = 0;
/*
* check descriptor
*/
if ( !__validate_desc( descriptor ))
{
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
"Error: SQL_INVALID_HANDLE" );
return SQL_INVALID_HANDLE;
}
function_entry( descriptor );
if ( log_info.log_flag )
{
sprintf( descriptor -> msg, "\n\t\tEntry:\
\n\t\t\tDescriptor = %p\
\n\t\t\tRec Number = %d\
\n\t\t\tField Ident = %s\
\n\t\t\tValue = %p\
\n\t\t\tBuffer Length = %d",
descriptor,
rec_number,
__desc_attr_as_string( s1, field_identifier ),
value,
(int)buffer_length );
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
descriptor -> msg );
}
thread_protect( SQL_HANDLE_DESC, descriptor );
if ( descriptor -> connection -> state < STATE_C4 )
{
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
"Error: HY010" );
__post_internal_error( &descriptor -> error,
ERROR_HY010, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
/*
* check status of statements associated with this descriptor
*/
if( __check_stmt_from_desc( descriptor, STATE_S8 ) ||
__check_stmt_from_desc( descriptor, STATE_S9 ) ||
__check_stmt_from_desc( descriptor, STATE_S10 ) ||
__check_stmt_from_desc( descriptor, STATE_S11 ) ||
__check_stmt_from_desc( descriptor, STATE_S12 ) ||
__check_stmt_from_desc( descriptor, STATE_S13 ) ||
__check_stmt_from_desc( descriptor, STATE_S14 ) ||
__check_stmt_from_desc( descriptor, STATE_S15 )) {
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
"Error: HY010" );
__post_internal_error( &descriptor -> error,
ERROR_HY010, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
if ( rec_number < 0 )
{
__post_internal_error( &descriptor -> error,
ERROR_07009, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
switch ( field_identifier )
{
/* Fixed-length fields: buffer_length is ignored */
case SQL_DESC_ALLOC_TYPE:
case SQL_DESC_ARRAY_SIZE:
case SQL_DESC_ARRAY_STATUS_PTR:
case SQL_DESC_BIND_OFFSET_PTR:
case SQL_DESC_BIND_TYPE:
case SQL_DESC_COUNT:
case SQL_DESC_ROWS_PROCESSED_PTR:
case SQL_DESC_AUTO_UNIQUE_VALUE:
case SQL_DESC_CASE_SENSITIVE:
case SQL_DESC_CONCISE_TYPE:
case SQL_DESC_DATA_PTR:
case SQL_DESC_DATETIME_INTERVAL_CODE:
case SQL_DESC_DATETIME_INTERVAL_PRECISION:
case SQL_DESC_DISPLAY_SIZE:
case SQL_DESC_FIXED_PREC_SCALE:
case SQL_DESC_INDICATOR_PTR:
case SQL_DESC_LENGTH:
case SQL_DESC_NULLABLE:
case SQL_DESC_NUM_PREC_RADIX:
case SQL_DESC_OCTET_LENGTH:
case SQL_DESC_OCTET_LENGTH_PTR:
case SQL_DESC_PARAMETER_TYPE:
case SQL_DESC_PRECISION:
case SQL_DESC_ROWVER:
case SQL_DESC_SCALE:
case SQL_DESC_SEARCHABLE:
case SQL_DESC_TYPE:
case SQL_DESC_UNNAMED:
case SQL_DESC_UNSIGNED:
case SQL_DESC_UPDATABLE:
isStrField = 0;
break;
/* Pointer to data: buffer_length must be valid */
case SQL_DESC_BASE_COLUMN_NAME:
case SQL_DESC_BASE_TABLE_NAME:
case SQL_DESC_CATALOG_NAME:
case SQL_DESC_LABEL:
case SQL_DESC_LITERAL_PREFIX:
case SQL_DESC_LITERAL_SUFFIX:
case SQL_DESC_LOCAL_TYPE_NAME:
case SQL_DESC_NAME:
case SQL_DESC_SCHEMA_NAME:
case SQL_DESC_TABLE_NAME:
case SQL_DESC_TYPE_NAME:
isStrField = 1;
break;
default:
isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER
&& buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT &&
buffer_length != SQL_IS_USMALLINT;
}
if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS)
{
__post_internal_error( &descriptor -> error,
ERROR_HY090, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 )
{
__post_internal_error( &descriptor -> error,
ERROR_07009, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT
&& value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT &&
value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM )
{
__post_internal_error( &descriptor -> error,
ERROR_HY105, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
if ( CHECK_SQLSETDESCFIELD( descriptor -> connection ))
{
ret = SQLSETDESCFIELD( descriptor -> connection,
descriptor -> driver_desc,
rec_number,
field_identifier,
value,
buffer_length );
}
else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection ))
{
SQLWCHAR *s1 = NULL;
if (isStrField)
{
s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL );
if (SQL_NTS != buffer_length)
{
buffer_length *= sizeof(SQLWCHAR);
}
}
else
{
s1 = value;
}
ret = SQLSETDESCFIELDW( descriptor -> connection,
descriptor -> driver_desc,
rec_number,
field_identifier,
s1,
buffer_length );
if (isStrField)
{
if (s1)
free(s1);
}
}
else
{
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
"Error: IM001" );
__post_internal_error( &descriptor -> error,
ERROR_IM001, NULL,
descriptor -> connection -> environment -> requested_version );
return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
}
if ( log_info.log_flag )
{
sprintf( descriptor -> msg,
"\n\t\tExit:[%s]",
__get_return_status( ret, s1 ));
dm_log_write( __FILE__,
__LINE__,
LOG_INFO,
LOG_INFO,
descriptor -> msg );
}
return function_return( SQL_HANDLE_DESC, descriptor, ret );
}
Commit Message: New Pre Source
CWE ID: CWE-119
Target: 1
Example 2:
Code: static ssize_t o2nm_node_ipv4_port_store(struct config_item *item,
const char *page, size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
unsigned long tmp;
char *p = (char *)page;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
if (tmp == 0)
return -EINVAL;
if (tmp >= (u16)-1)
return -ERANGE;
if (test_and_set_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EBUSY;
node->nd_ipv4_port = htons(tmp);
return count;
}
Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[[email protected]: v2]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void strictTypeCheckingFloatAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectPythonV8Internal::strictTypeCheckingFloatAttributeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: struct gendisk *alloc_disk(int minors)
{
return alloc_disk_node(minors, NUMA_NO_NODE);
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SCTP_STATIC int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
int rc = -ENOTCONN;
sctp_lock_sock(sk);
/*
* SEQPACKET-style sockets in LISTENING state are valid, for
* SCTP, so only discard TCP-style sockets in LISTENING state.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
goto out;
switch (cmd) {
case SIOCINQ: {
struct sk_buff *skb;
unsigned int amount = 0;
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/*
* We will only return the amount of this packet since
* that is all that will be read.
*/
amount = skb->len;
}
rc = put_user(amount, (int __user *)arg);
break;
}
default:
rc = -ENOIOCTLCMD;
break;
}
out:
sctp_release_sock(sk);
return rc;
}
Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[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: void OpenTwoTabs(const GURL& first_url, const GURL& second_url) {
content::WindowedNotificationObserver load1(
content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::NotificationService::AllSources());
OpenURLParams open1(first_url, content::Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false);
browser()->OpenURL(open1);
load1.Wait();
content::WindowedNotificationObserver load2(
content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::NotificationService::AllSources());
OpenURLParams open2(second_url, content::Referrer(),
WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui::PAGE_TRANSITION_TYPED, false);
browser()->OpenURL(open2);
load2.Wait();
ASSERT_EQ(2, tsm()->count());
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
Target: 1
Example 2:
Code: void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
std::vector<storage::URLRequestAutoMountHandler>* handlers) {
for (size_t i = 0; i < extra_parts_.size(); ++i)
extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct json_object* json_tokener_parse_ex(struct json_tokener *tok,
const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
#ifdef HAVE_SETLOCALE
char *oldlocale=NULL, *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale) oldlocale = strdup(tmplocale);
setlocale(LC_NUMERIC, "C");
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
while (PEEK_CHAR(c, tok)) {
redo_char:
switch(state) {
case json_tokener_state_eatws:
/* Advance until we change state */
while (isspace((int)c)) {
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {
printbuf_reset(tok->pb);
printbuf_memappend_fast(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
} else {
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch(c) {
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT) {
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
#if defined(__GNUC__)
case '0' ... '9':
#else
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
#endif
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default:
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
break;
case json_tokener_state_finish:
if(tok->depth == 0) goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' */
{
int size;
int size_inf;
int is_negative = 0;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_inf = json_min(tok->st_pos+1, json_inf_str_len);
char *infbuf = tok->pb->buf;
if (*infbuf == '-')
{
infbuf++;
is_negative = 1;
}
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||
(strncmp(json_inf_str, infbuf, size_inf) == 0)
)
{
if (tok->st_pos == json_inf_str_len)
{
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_nan = json_min(tok->st_pos+1, json_nan_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0)
|| (strncmp(json_null_str, tok->pb->buf, size) == 0)
) {
if (tok->st_pos == json_null_str_len) {
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)
)
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if(c == '*') {
state = json_tokener_state_comment;
} else if(c == '/') {
state = json_tokener_state_comment_eol;
} else {
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_fast(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '*') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '\n') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_fast(tok->pb, &c, 1);
if(c == '/') {
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
} else {
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch(c) {
case '"':
case '\\':
case '/':
printbuf_memappend_fast(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1);
else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1);
else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1);
else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1);
else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default:
tok->err = json_tokener_error_parse_string;
goto out;
}
break;
case json_tokener_state_escape_unicode:
{
unsigned int got_hi_surrogate = 0;
/* Handle a 4-byte sequence, or two sequences if a surrogate pair */
while(1) {
if(strchr(json_hex_chars, c)) {
tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));
if(tok->st_pos == 4) {
unsigned char unescaped_utf[4];
if (got_hi_surrogate) {
if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);
} else {
/* Hi surrogate was not followed by a low surrogate */
/* Replace the hi and process the rest normally */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
got_hi_surrogate = 0;
}
if (tok->ucs_char < 0x80) {
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);
} else if (tok->ucs_char < 0x800) {
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);
} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {
/* Got a high surrogate. Remember it and look for the
* the beginning of another sequence, which should be the
* low surrogate.
*/
got_hi_surrogate = tok->ucs_char;
/* Not at end, and the next two chars should be "\u" */
if ((tok->char_offset+1 != len) &&
(tok->char_offset+2 != len) &&
(str[1] == '\\') &&
(str[2] == 'u'))
{
/* Advance through the 16 bit surrogate, and move on to the
* next sequence. The next step is to process the following
* characters.
*/
if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
/* Advance to the first char of the next sequence and
* continue processing with the next sequence.
*/
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
tok->ucs_char = 0;
tok->st_pos = 0;
continue; /* other json_tokener_state_escape_unicode */
} else {
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the hi surrogate
* and pretend we finished.
*/
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
} else if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Got a low surrogate not preceded by a high */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
} else if (tok->ucs_char < 0x10000) {
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);
} else if (tok->ucs_char < 0x110000) {
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);
} else {
/* Don't know what we got--insert the replacement char */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
state = saved_state;
break;
}
} else {
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
if (got_hi_surrogate) /* Clean up any pending chars */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
}
}
break;
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_fast(tok->pb, &c, 1);
size1 = json_min(tok->st_pos+1, json_true_str_len);
size2 = json_min(tok->st_pos+1, json_false_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0)
|| (strncmp(json_true_str, tok->pb->buf, size1) == 0)
) {
if(tok->st_pos == json_true_str_len) {
current = json_object_new_boolean(1);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0)
|| (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {
if(tok->st_pos == json_false_str_len) {
current = json_object_new_boolean(0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len=0;
while(c && strchr(json_number_chars, c)) {
++case_len;
if(c == '.' || c == 'e' || c == 'E')
tok->is_double = 1;
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, case_len);
goto out;
}
}
if (case_len>0)
printbuf_memappend_fast(tok->pb, case_start, case_len);
if (tok->pb->buf[0] == '-' && case_len == 1 &&
(c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
goto redo_char;
}
}
{
int64_t num64;
double numd;
if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {
if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {
/* in strict mode, number must not start with 0 */
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
}
else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
} else {
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if(c == ']') {
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else {
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
json_object_array_add(current, obj);
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if(c == ']') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if(c == '}') {
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if (c == '"' || c == '\'') {
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
} else {
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
obj_field_name = strdup(tok->pb->buf);
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if(c == ':') {
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
json_object_object_add(current, obj_field_name, obj);
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
if(c == '}') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
if (!ADVANCE_CHAR(str, tok))
goto out;
} /* while(POP_CHAR) */
Commit Message: Patch to address the following issues:
* CVE-2013-6371: hash collision denial of service
* CVE-2013-6370: buffer overflow if size_t is larger than int
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: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
Commit Message: Add bounds check before length read
CWE ID: CWE-125
Target: 1
Example 2:
Code: void comps_mrtree_values_walk(COMPS_MRTree * rt, void* udata,
void (*walk_f)(void*, void*)) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it, *it2;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, NULL);
comps_hslist_append(tmplist, rt->subnodes, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = (COMPS_HSList*)it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist,
((COMPS_MRTreeData*)it->data)->subnodes, 0);
}
for (it2 = (COMPS_HSListItem*)((COMPS_MRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
walk_f(udata, it2->data);
}
}
}
comps_hslist_destroy(&tmplist);
}
Commit Message: Fix UAF in comps_objmrtree_unite function
The added field is not used at all in many places and it is probably the
left-over of some copy-paste.
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 ip_options_get_finish(struct net *net, struct ip_options **optp,
struct ip_options *opt, int optlen)
{
while (optlen & 3)
opt->__data[optlen++] = IPOPT_END;
opt->optlen = optlen;
if (optlen && ip_options_compile(net, opt, NULL)) {
kfree(opt);
return -EINVAL;
}
kfree(*optp);
*optp = opt;
return 0;
}
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
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: BufferMeta(const sp<GraphicBuffer> &graphicBuffer)
: mGraphicBuffer(graphicBuffer),
mIsBackup(false) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Target: 1
Example 2:
Code: static bool IsHTMLQuote(UChar c) {
return (c == '"' || c == '\'');
}
Commit Message: Restrict the xss audit report URL to same origin
BUG=441275
[email protected],[email protected]
Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d
Reviewed-on: https://chromium-review.googlesource.com/768367
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516666}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 stack_trace_open(struct inode *inode, struct file *file)
{
return seq_open(file, &stack_trace_seq_ops);
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
struct path *dir, char *type, unsigned long flags)
{
struct path path;
struct file_system_type *fstype = NULL;
const char *requested_type = NULL;
const char *requested_dir_name = NULL;
const char *requested_dev_name = NULL;
struct tomoyo_path_info rtype;
struct tomoyo_path_info rdev;
struct tomoyo_path_info rdir;
int need_dev = 0;
int error = -ENOMEM;
/* Get fstype. */
requested_type = tomoyo_encode(type);
if (!requested_type)
goto out;
rtype.name = requested_type;
tomoyo_fill_path_info(&rtype);
/* Get mount point. */
requested_dir_name = tomoyo_realpath_from_path(dir);
if (!requested_dir_name) {
error = -ENOMEM;
goto out;
}
rdir.name = requested_dir_name;
tomoyo_fill_path_info(&rdir);
/* Compare fs name. */
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) {
need_dev = -1; /* dev_name is a directory */
} else {
fstype = get_fs_type(type);
if (!fstype) {
error = -ENODEV;
goto out;
}
if (fstype->fs_flags & FS_REQUIRES_DEV)
/* dev_name is a block device file. */
need_dev = 1;
}
if (need_dev) {
/* Get mount point or device file. */
if (kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
error = -ENOENT;
goto out;
}
requested_dev_name = tomoyo_realpath_from_path(&path);
path_put(&path);
if (!requested_dev_name) {
error = -ENOENT;
goto out;
}
} else {
/* Map dev_name to "<NULL>" if no dev_name given. */
if (!dev_name)
dev_name = "<NULL>";
requested_dev_name = tomoyo_encode(dev_name);
if (!requested_dev_name) {
error = -ENOMEM;
goto out;
}
}
rdev.name = requested_dev_name;
tomoyo_fill_path_info(&rdev);
r->param_type = TOMOYO_TYPE_MOUNT_ACL;
r->param.mount.need_dev = need_dev;
r->param.mount.dev = &rdev;
r->param.mount.dir = &rdir;
r->param.mount.type = &rtype;
r->param.mount.flags = flags;
do {
tomoyo_check_acl(r, tomoyo_check_mount_acl);
error = tomoyo_audit_mount_log(r);
} while (error == TOMOYO_RETRY_REQUEST);
out:
kfree(requested_dev_name);
kfree(requested_dir_name);
if (fstype)
put_filesystem(fstype);
kfree(requested_type);
return error;
}
Commit Message: TOMOYO: Fix oops in tomoyo_mount_acl().
In tomoyo_mount_acl() since 2.6.36, kern_path() was called without checking
dev_name != NULL. As a result, an unprivileged user can trigger oops by issuing
mount(NULL, "/", "ext3", 0, NULL) request.
Fix this by checking dev_name != NULL before calling kern_path(dev_name).
Signed-off-by: Tetsuo Handa <[email protected]>
Cc: [email protected]
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int find_next_best_node(int node, nodemask_t *used_nodes)
{
int i, n, val, min_val, best_node = -1;
min_val = INT_MAX;
for (i = 0; i < nr_node_ids; i++) {
/* Start at @node */
n = (node + i) % nr_node_ids;
if (!nr_cpus_node(n))
continue;
/* Skip already used nodes */
if (node_isset(n, *used_nodes))
continue;
/* Simple min distance search */
val = node_distance(node, n);
if (val < min_val) {
min_val = val;
best_node = n;
}
}
if (best_node != -1)
node_set(best_node, *used_nodes);
return best_node;
}
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: static unsigned int perf_poll(struct file *file, poll_table *wait)
{
struct perf_event *event = file->private_data;
struct ring_buffer *rb;
unsigned int events = POLLHUP;
poll_wait(file, &event->waitq, wait);
if (is_event_hup(event))
return events;
/*
* Pin the event->rb by taking event->mmap_mutex; otherwise
* perf_event_set_output() can swizzle our rb and make us miss wakeups.
*/
mutex_lock(&event->mmap_mutex);
rb = event->rb;
if (rb)
events = atomic_xchg(&rb->poll, 0);
mutex_unlock(&event->mmap_mutex);
return events;
}
Commit Message: perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <[email protected]>
Tested-by: Sasha Levin <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
u32 rmr, u64 to,
u32 xdr_off, int write_len,
struct svc_rdma_req_map *vec)
{
struct ib_rdma_wr write_wr;
struct ib_sge *sge;
int xdr_sge_no;
int sge_no;
int sge_bytes;
int sge_off;
int bc;
struct svc_rdma_op_ctxt *ctxt;
if (vec->count > RPCSVC_MAXPAGES) {
pr_err("svcrdma: Too many pages (%lu)\n", vec->count);
return -EIO;
}
dprintk("svcrdma: RDMA_WRITE rmr=%x, to=%llx, xdr_off=%d, "
"write_len=%d, vec->sge=%p, vec->count=%lu\n",
rmr, (unsigned long long)to, xdr_off,
write_len, vec->sge, vec->count);
ctxt = svc_rdma_get_context(xprt);
ctxt->direction = DMA_TO_DEVICE;
sge = ctxt->sge;
/* Find the SGE associated with xdr_off */
for (bc = xdr_off, xdr_sge_no = 1; bc && xdr_sge_no < vec->count;
xdr_sge_no++) {
if (vec->sge[xdr_sge_no].iov_len > bc)
break;
bc -= vec->sge[xdr_sge_no].iov_len;
}
sge_off = bc;
bc = write_len;
sge_no = 0;
/* Copy the remaining SGE */
while (bc != 0) {
sge_bytes = min_t(size_t,
bc, vec->sge[xdr_sge_no].iov_len-sge_off);
sge[sge_no].length = sge_bytes;
sge[sge_no].addr =
dma_map_xdr(xprt, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(xprt->sc_cm_id->device,
sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(xprt, ctxt);
sge[sge_no].lkey = xprt->sc_pd->local_dma_lkey;
ctxt->count++;
sge_off = 0;
sge_no++;
xdr_sge_no++;
if (xdr_sge_no > vec->count) {
pr_err("svcrdma: Too many sges (%d)\n", xdr_sge_no);
goto err;
}
bc -= sge_bytes;
if (sge_no == xprt->sc_max_sge)
break;
}
/* Prepare WRITE WR */
memset(&write_wr, 0, sizeof write_wr);
ctxt->cqe.done = svc_rdma_wc_write;
write_wr.wr.wr_cqe = &ctxt->cqe;
write_wr.wr.sg_list = &sge[0];
write_wr.wr.num_sge = sge_no;
write_wr.wr.opcode = IB_WR_RDMA_WRITE;
write_wr.wr.send_flags = IB_SEND_SIGNALED;
write_wr.rkey = rmr;
write_wr.remote_addr = to;
/* Post It */
atomic_inc(&rdma_stat_write);
if (svc_rdma_send(xprt, &write_wr.wr))
goto err;
return write_len - bc;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
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
Target: 1
Example 2:
Code: bool IsEqualForTesting(const SendTabToSelfEntry& a,
const SendTabToSelfEntry& b) {
return a.GetGUID() == b.GetGUID() && a.GetURL() == b.GetURL() &&
a.GetTitle() == b.GetTitle() &&
a.GetDeviceName() == b.GetDeviceName() &&
a.GetTargetDeviceSyncCacheGuid() == b.GetTargetDeviceSyncCacheGuid() &&
a.GetSharedTime() == b.GetSharedTime() &&
a.GetOriginalNavigationTime() == b.GetOriginalNavigationTime();
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) {
CPU_MODEL *cpu;
ut64 offset;
if (!op) {
return 2;
}
cpu = get_cpu_model (anal->cpu);
if (anal->esil) {
offset = 0;
r_anal_esil_reg_write (anal->esil, "_prog", offset);
offset += (1 << cpu->pc);
r_anal_esil_reg_write (anal->esil, "_io", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start"));
r_anal_esil_reg_write (anal->esil, "_sram", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size"));
r_anal_esil_reg_write (anal->esil, "_eeprom", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size"));
r_anal_esil_reg_write (anal->esil, "_page", offset);
}
avr_op_analyze (anal, op, addr, buf, len, cpu);
return op->size;
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
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 double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
* and so must be adjusted for low bit depth grayscale:
*/
if (out_depth <= 8)
{
if (pm->log8 == 0) /* switched off */
return 256;
if (out_depth < 8)
return pm->log8 / 255 * ((1<<out_depth)-1);
return pm->log8;
}
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
{
if (pm->log16 == 0)
return 65536;
return pm->log16;
}
/* This is the case where the value was calculated at 8-bit precision then
* scaled to 16 bits.
*/
if (pm->log8 == 0)
return 65536;
return pm->log8 * 257;
}
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: DevToolsDataSource::~DevToolsDataSource() {
for (const auto& pair : pending_) {
delete pair.first;
pair.second.Run(
new base::RefCountedStaticMemory(kHttpNotFound, strlen(kHttpNotFound)));
}
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
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: Element* Document::ActiveElement() const {
if (Element* element = AdjustedFocusedElement())
return element;
return body();
}
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: static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MaxTextExtent];
CINInfo
cin;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4],
*pixels;
/*
Open image file.
*/
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);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=(int) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property);
(void) ResetMagickMemory(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,
sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
profile=BlobToStringInfo((const void *) NULL,cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile);
profile=DestroyStringInfo(profile);
}
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
(void) ReadBlobByte(image);
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping)
{
(void) CloseBlob(image);
return(image);
}
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,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;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: BGD_DECLARE(int) gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id)
{
if (im == NULL || (uintmax_t)id > GD_METHOD_COUNT) {
return 0;
}
switch (id) {
case GD_NEAREST_NEIGHBOUR:
case GD_WEIGHTED4:
im->interpolation = NULL;
break;
/* generic versions*/
/* GD_BILINEAR_FIXED and GD_BICUBIC_FIXED are kept for BC reasons */
case GD_BILINEAR_FIXED:
case GD_LINEAR:
im->interpolation = filter_linear;
break;
case GD_BELL:
im->interpolation = filter_bell;
break;
case GD_BESSEL:
im->interpolation = filter_bessel;
break;
case GD_BICUBIC_FIXED:
case GD_BICUBIC:
im->interpolation = filter_bicubic;
break;
case GD_BLACKMAN:
im->interpolation = filter_blackman;
break;
case GD_BOX:
im->interpolation = filter_box;
break;
case GD_BSPLINE:
im->interpolation = filter_bspline;
break;
case GD_CATMULLROM:
im->interpolation = filter_catmullrom;
break;
case GD_GAUSSIAN:
im->interpolation = filter_gaussian;
break;
case GD_GENERALIZED_CUBIC:
im->interpolation = filter_generalized_cubic;
break;
case GD_HERMITE:
im->interpolation = filter_hermite;
break;
case GD_HAMMING:
im->interpolation = filter_hamming;
break;
case GD_HANNING:
im->interpolation = filter_hanning;
break;
case GD_MITCHELL:
im->interpolation = filter_mitchell;
break;
case GD_POWER:
im->interpolation = filter_power;
break;
case GD_QUADRATIC:
im->interpolation = filter_quadratic;
break;
case GD_SINC:
im->interpolation = filter_sinc;
break;
case GD_TRIANGLE:
im->interpolation = filter_triangle;
break;
case GD_DEFAULT:
id = GD_LINEAR;
im->interpolation = filter_linear;
default:
return 0;
break;
}
im->interpolation_id = id;
return 1;
}
Commit Message: Fix potential unsigned underflow
No need to decrease `u`, so we don't do it. While we're at it, we also factor
out the overflow check of the loop, what improves performance and readability.
This issue has been reported by Stefan Esser to [email protected].
CWE ID: CWE-191
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: update_stat(char *port, uint64_t traffic)
{
if (verbose) {
LOGI("update traffic %" PRIu64 " for port %s", traffic, port);
}
void *ret = cork_hash_table_get(server_table, (void *)port);
if (ret != NULL) {
struct server *server = (struct server *)ret;
server->traffic = traffic;
}
}
Commit Message: Fix #1734
CWE ID: CWE-78
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 perf_event_comm_output(struct perf_event *event,
struct perf_comm_event *comm_event)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int size = comm_event->event_id.header.size;
int ret;
perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event,
comm_event->event_id.header.size, 0, 0);
if (ret)
goto out;
comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
perf_output_put(&handle, comm_event->event_id);
__output_copy(&handle, comm_event->comm,
comm_event->comm_size);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
out:
comm_event->event_id.header.size = size;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: int _yr_re_alloc_storage(
RE_THREAD_STORAGE** storage)
{
*storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
if (*storage == NULL)
{
*storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE));
if (*storage == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*storage)->fiber_pool.fiber_count = 0;
(*storage)->fiber_pool.fibers.head = NULL;
(*storage)->fiber_pool.fibers.tail = NULL;
FAIL_ON_ERROR(
yr_thread_storage_set_value(&thread_storage_key, *storage));
}
return ERROR_SUCCESS;
}
Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
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: resetLppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */
UCHAR highBandStartSb, /*!< High band area: start subband */
UCHAR *v_k_master, /*!< Master table */
UCHAR numMaster, /*!< Valid entries in master table */
UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */
UCHAR noNoiseBands, /*!< Number of noise bands */
UCHAR usb, /*!< High band area: stop subband */
UINT fs /*!< SBR output sampling frequency */
)
{
TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings;
PATCH_PARAM *patchParam = pSettings->patchParam;
int i, patch;
int targetStopBand;
int sourceStartBand;
int patchDistance;
int numBandsInPatch;
int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling terms*/
int xoverOffset = highBandStartSb - lsb; /* Calculate distance in QMF bands between k0 and kx */
int startFreqHz;
int desiredBorder;
usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with float code). */
/*
* Plausibility check
*/
if ( lsb - SHIFT_START_SB < 4 ) {
return SBRDEC_UNSUPPORTED_CONFIG;
}
/*
* Initialize the patching parameter
*/
/* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */
desiredBorder = (((2048000*2) / fs) + 1) >> 1;
desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster, 1); /* Adapt region to master-table */
/* First patch */
sourceStartBand = SHIFT_START_SB + xoverOffset;
targetStopBand = lsb + xoverOffset; /* upperBand */
/* Even (odd) numbered channel must be patched to even (odd) numbered channel */
patch = 0;
while(targetStopBand < usb) {
/* Too many patches?
Allow MAX_NUM_PATCHES+1 patches here.
we need to check later again, since patch might be the highest patch
AND contain less than 3 bands => actual number of patches will be reduced by 1.
*/
if (patch > MAX_NUM_PATCHES) {
return SBRDEC_UNSUPPORTED_CONFIG;
}
patchParam[patch].guardStartBand = targetStopBand;
patchParam[patch].targetStartBand = targetStopBand;
numBandsInPatch = desiredBorder - targetStopBand; /* Get the desired range of the patch */
if ( numBandsInPatch >= lsb - sourceStartBand ) {
/* Desired number bands are not available -> patch whole source range */
patchDistance = targetStopBand - sourceStartBand; /* Get the targetOffset */
patchDistance = patchDistance & ~1; /* Rounding off odd numbers and make all even */
numBandsInPatch = lsb - (targetStopBand - patchDistance); /* Update number of bands to be patched */
numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch, v_k_master, numMaster, 0) -
targetStopBand; /* Adapt region to master-table */
}
/* Desired number bands are available -> get the minimal even patching distance */
patchDistance = numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */
patchDistance = (patchDistance + 1) & ~1; /* Rounding up odd numbers and make all even */
if (numBandsInPatch > 0) {
patchParam[patch].sourceStartBand = targetStopBand - patchDistance;
patchParam[patch].targetBandOffs = patchDistance;
patchParam[patch].numBandsInPatch = numBandsInPatch;
patchParam[patch].sourceStopBand = patchParam[patch].sourceStartBand + numBandsInPatch;
targetStopBand += patchParam[patch].numBandsInPatch;
patch++;
}
/* All patches but first */
sourceStartBand = SHIFT_START_SB;
/* Check if we are close to desiredBorder */
if( desiredBorder - targetStopBand < 3) /* MPEG doc */
{
desiredBorder = usb;
}
}
patch--;
/* If highest patch contains less than three subband: skip it */
if ( (patch>0) && (patchParam[patch].numBandsInPatch < 3) ) {
patch--;
targetStopBand = patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch;
}
/* now check if we don't have one too many */
if (patch >= MAX_NUM_PATCHES) {
return SBRDEC_UNSUPPORTED_CONFIG;
}
pSettings->noOfPatches = patch + 1;
/* Check lowest and highest source subband */
pSettings->lbStartPatching = targetStopBand;
pSettings->lbStopPatching = 0;
for ( patch = 0; patch < pSettings->noOfPatches; patch++ ) {
pSettings->lbStartPatching = fixMin( pSettings->lbStartPatching, patchParam[patch].sourceStartBand );
pSettings->lbStopPatching = fixMax( pSettings->lbStopPatching, patchParam[patch].sourceStopBand );
}
for(i = 0 ; i < noNoiseBands; i++){
pSettings->bwBorders[i] = noiseBandTable[i+1];
}
/*
* Choose whitening factors
*/
startFreqHz = ( (lsb + xoverOffset)*fs ) >> 7; /* Shift does a division by 2*(64) */
for( i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++ )
{
if( startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i])
break;
}
i--;
pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0];
pSettings->whFactors.transitionLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][1];
pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2];
pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3];
pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4];
return SBRDEC_OK;
}
Commit Message: Fix out of bound memory access in lppTransposer
In TRANSPOSER_SETTINGS, initialize the whole bwBorders array to a
reasonable value to guarantee correct termination in while loop
in lppTransposer function. This fixes the reported bug.
For completeness:
- clear the whole bwIndex array instead of noOfPatches entries only.
- abort criterion in while loop to prevent potential
infinite loop, and limit bwIndex[patch] to a valid range.
Test: see bug for malicious content, decoded with "stagefright -s -a"
Bug: 65280786
Change-Id: I16ed2e1c0f1601926239a652ca20a91284151843
(cherry picked from commit 6d3dd40e204bf550abcfa589bd9615df8778e118)
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: MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL)
{
ALOGV("constructor");
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != NULL) {
mMediaRecorder = service->createMediaRecorder(opPackageName);
}
if (mMediaRecorder != NULL) {
mCurrentState = MEDIA_RECORDER_IDLE;
}
doCleanUp();
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int fuse_direct_mmap(struct file *file, struct vm_area_struct *vma)
{
/* Can't provide the coherency needed for MAP_SHARED */
if (vma->vm_flags & VM_MAYSHARE)
return -ENODEV;
invalidate_inode_pages2(file->f_mapping);
return generic_file_mmap(file, vma);
}
Commit Message: fuse: verify ioctl retries
Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY
doesn't overflow iov_length().
Signed-off-by: Miklos Szeredi <[email protected]>
CC: Tejun Heo <[email protected]>
CC: <[email protected]> [2.6.31+]
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: summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
int indexed)
{
fflush(stderr);
if (who)
printf("\nGamma correction with %s:\n", who);
else
printf("\nBasic gamma correction:\n");
if (low_bit_depth)
{
print_one(" 2 bit gray: ", pm->error_gray_2);
print_one(" 4 bit gray: ", pm->error_gray_4);
print_one(" 8 bit gray: ", pm->error_gray_8);
print_one(" 8 bit color:", pm->error_color_8);
if (indexed)
print_one(" indexed: ", pm->error_indexed);
}
print_one("16 bit gray: ", pm->error_gray_16);
print_one("16 bit color:", pm->error_color_16);
fflush(stdout);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
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: RTCVoidRequestTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCVoidRequest& request, bool succeeded)
: MethodTask<MockWebRTCPeerConnectionHandler>(object)
, m_request(request)
, m_succeeded(succeeded)
{
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: char EVUTIL_TOUPPER_(char c)
{
return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
}
Commit Message: evutil_parse_sockaddr_port(): fix buffer overflow
@asn-the-goblin-slayer:
"Length between '[' and ']' is cast to signed 32 bit integer on line 1815. Is
the length is more than 2<<31 (INT_MAX), len will hold a negative value.
Consequently, it will pass the check at line 1816. Segfault happens at line
1819.
Generate a resolv.conf with generate-resolv.conf, then compile and run
poc.c. See entry-functions.txt for functions in tor that might be
vulnerable.
Please credit 'Guido Vranken' for this discovery through the Tor bug bounty
program."
Reproducer for gdb (https://gist.github.com/azat/be2b0d5e9417ba0dfe2c):
start
p (1ULL<<31)+1ULL
# $1 = 2147483649
p malloc(sizeof(struct sockaddr))
# $2 = (void *) 0x646010
p malloc(sizeof(int))
# $3 = (void *) 0x646030
p malloc($1)
# $4 = (void *) 0x7fff76a2a010
p memset($4, 1, $1)
# $5 = 1990369296
p (char *)$4
# $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
set $6[0]='['
set $6[$1]=']'
p evutil_parse_sockaddr_port($4, $2, $3)
# $7 = -1
Before:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb)
Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:36
After:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb) $7 = -1
(gdb) (gdb) quit
Fixes: #318
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: extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size > 512)
return 0;
net::ProxyBypassRules rules;
std::string input(data, data + size);
rules.ParseFromString(input);
rules.ParseFromStringUsingSuffixMatching(input);
return 0;
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebGLRenderingContextBase::TexImageHelperImageData(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint border,
GLenum format,
GLenum type,
GLsizei depth,
GLint xoffset,
GLint yoffset,
GLint zoffset,
ImageData* pixels,
const IntRect& source_image_rect,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
DCHECK(pixels);
if (pixels->data()->BufferBase()->IsNeutered()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name,
"The source data has been neutered.");
return;
}
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target,
level, internalformat, pixels->width(), pixels->height(),
depth, border, format, type, xoffset, yoffset, zoffset))
return;
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(
func_name, function_id, pixels, source_image_rect, depth,
unpack_image_height, &selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = source_image_rect;
if (unpack_flip_y_) {
adjusted_source_image_rect.SetY(pixels->height() -
adjusted_source_image_rect.MaxY());
}
Vector<uint8_t> data;
bool need_conversion = true;
if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA &&
type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
if (!WebGLImageConversion::ExtractImageData(
pixels->data()->Data(),
WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(),
adjusted_source_image_rect, depth, unpack_image_height, format,
type, unpack_flip_y_, unpack_premultiply_alpha_, data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data();
if (function_id == kTexImage2D) {
DCHECK_EQ(unpack_image_height, 0);
TexImage2DBase(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), border, format, type, bytes);
} else if (function_id == kTexSubImage2D) {
DCHECK_EQ(unpack_image_height, 0);
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type, bytes);
} else {
GLint upload_height = adjusted_source_image_rect.Height();
if (unpack_image_height) {
upload_height = unpack_image_height;
}
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(target, level, internalformat,
adjusted_source_image_rect.Width(), upload_height,
depth, border, format, type, bytes);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
upload_height, depth, format, type, bytes);
}
}
}
Commit Message: fix incorrect TexImage3D params w/ UNPACK_IMAGE_HEIGHT
Bug: 804123
Test: http://github.com/KhronosGroup/WebGL/pull/2646
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ifbce9b93f0b35817881e1e34930cbac22a1e8b98
Reviewed-on: https://chromium-review.googlesource.com/1053573
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Kai Ninomiya <[email protected]>
Cr-Commit-Position: refs/heads/master@{#558962}
CWE ID:
Target: 1
Example 2:
Code: void GLManager::SetSurface(gl::GLSurface* surface) {
decoder_->SetSurface(surface);
MakeCurrent();
}
Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data.
In linux and android, we are seeing an issue where texture data from one
tab overwrites the texture data of another tab. This is happening for apps
which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D.
Due to a bug in virtual context save/restore code for above texture formats,
the texture data is not properly restored while switching tabs. Hence
texture data from one tab overwrites other.
This CL has fix for that issue, an update for existing test expectations
and a new unit test for this bug.
Bug: 788448
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: Ie933984cdd2d1381f42eb4638f730c8245207a28
Reviewed-on: https://chromium-review.googlesource.com/930327
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: vikas soni <[email protected]>
Cr-Commit-Position: refs/heads/master@{#539111}
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 FormAssociatedElement::setForm(HTMLFormElement* newForm)
{
if (m_form == newForm)
return;
willChangeForm();
if (m_form)
m_form->removeFormElement(this);
m_form = newForm;
if (m_form)
m_form->registerFormElement(*this);
didChangeForm();
}
Commit Message: Fix a crash when a form control is in a past naems map of a demoted form element.
Note that we wanted to add the protector in FormAssociatedElement::setForm(),
but we couldn't do it because it is called from the constructor.
BUG=326854
TEST=automated.
Review URL: https://codereview.chromium.org/105693013
git-svn-id: svn://svn.chromium.org/blink/trunk@163680 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-287
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int date_from_ISO8601 (const char *text, time_t * value) {
struct tm tm;
* Begin Time Functions *
***********************/
static int date_from_ISO8601 (const char *text, time_t * value) {
struct tm tm;
int n;
int i;
char buf[18];
if (strchr (text, '-')) {
char *p = (char *) text, *p2 = buf;
}
if (*p != '-') {
*p2 = *p;
p2++;
}
p++;
}
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool Element::hasAttribute(const AtomicString& localName) const
{
if (!elementData())
return false;
synchronizeAttribute(localName);
return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
}
Commit Message: Set Attr.ownerDocument in Element#setAttributeNode()
Attr objects can move across documents by setAttributeNode().
So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded().
BUG=248950
TEST=set-attribute-node-from-iframe.html
Review URL: https://chromiumcodereview.appspot.com/17583003
git-svn-id: svn://svn.chromium.org/blink/trunk@152938 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: bool BluetoothDeviceChromeOS::ExpectingPasskey() const {
return !passkey_callback_.is_null();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: v8::Local<v8::Value> V8Proxy::instrumentedCallFunction(Frame* frame, v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> args[])
{
V8GCController::checkMemoryUsage();
if (V8RecursionScope::recursionLevel() >= kMaxRecursionDepth)
return handleMaxRecursionDepthExceeded();
ScriptExecutionContext* context = frame ? frame->document() : 0;
InspectorInstrumentationCookie cookie;
if (InspectorInstrumentation::hasFrontends() && context) {
String resourceName;
int lineNumber;
resourceInfo(function, resourceName, lineNumber);
cookie = InspectorInstrumentation::willCallFunction(context, resourceName, lineNumber);
}
v8::Local<v8::Value> result;
{
#if PLATFORM(CHROMIUM)
TRACE_EVENT1("v8", "v8.callFunction", "callsite", resourceString(function).utf8());
#endif
V8RecursionScope recursionScope(context);
result = function->Call(receiver, argc, args);
}
InspectorInstrumentation::didCallFunction(cookie);
if (v8::V8::IsDead())
handleFatalErrorInV8();
return result;
}
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: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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(curl_pause)
{
zend_long bitmask;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zid, &bitmask) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
RETURN_LONG(curl_easy_pause(ch->cp, bitmask));
}
Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int lzo1x_decompress_safe(const unsigned char *in, size_t in_len,
unsigned char *out, size_t *out_len)
{
unsigned char *op;
const unsigned char *ip;
size_t t, next;
size_t state = 0;
const unsigned char *m_pos;
const unsigned char * const ip_end = in + in_len;
unsigned char * const op_end = out + *out_len;
op = out;
ip = in;
if (unlikely(in_len < 3))
goto input_overrun;
if (*ip > 17) {
t = *ip++ - 17;
if (t < 4) {
next = t;
goto match_next;
}
goto copy_literal_run;
}
for (;;) {
t = *ip++;
if (t < 16) {
if (likely(state == 0)) {
if (unlikely(t == 0)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 15 + *ip++;
}
t += 3;
copy_literal_run:
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(t + 15) && HAVE_OP(t + 15))) {
const unsigned char *ie = ip + t;
unsigned char *oe = op + t;
do {
COPY8(op, ip);
op += 8;
ip += 8;
COPY8(op, ip);
op += 8;
ip += 8;
} while (ip < ie);
ip = ie;
op = oe;
} else
#endif
{
NEED_OP(t);
NEED_IP(t + 3);
do {
*op++ = *ip++;
} while (--t > 0);
}
state = 4;
continue;
} else if (state != 4) {
next = t & 3;
m_pos = op - 1;
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
TEST_LB(m_pos);
NEED_OP(2);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
goto match_next;
} else {
next = t & 3;
m_pos = op - (1 + M2_MAX_OFFSET);
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
t = 3;
}
} else if (t >= 64) {
next = t & 3;
m_pos = op - 1;
m_pos -= (t >> 2) & 7;
m_pos -= *ip++ << 3;
t = (t >> 5) - 1 + (3 - 1);
} else if (t >= 32) {
t = (t & 31) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 31 + *ip++;
NEED_IP(2);
}
m_pos = op - 1;
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
} else {
m_pos = op;
m_pos -= (t & 8) << 11;
t = (t & 7) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 7 + *ip++;
NEED_IP(2);
}
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
if (m_pos == op)
goto eof_found;
m_pos -= 0x4000;
}
TEST_LB(m_pos);
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (op - m_pos >= 8) {
unsigned char *oe = op + t;
if (likely(HAVE_OP(t + 15))) {
do {
COPY8(op, m_pos);
op += 8;
m_pos += 8;
COPY8(op, m_pos);
op += 8;
m_pos += 8;
} while (op < oe);
op = oe;
if (HAVE_IP(6)) {
state = next;
COPY4(op, ip);
op += next;
ip += next;
continue;
}
} else {
NEED_OP(t);
do {
*op++ = *m_pos++;
} while (op < oe);
}
} else
#endif
{
unsigned char *oe = op + t;
NEED_OP(t);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
m_pos += 2;
do {
*op++ = *m_pos++;
} while (op < oe);
}
match_next:
state = next;
t = next;
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(6) && HAVE_OP(4))) {
COPY4(op, ip);
op += t;
ip += t;
} else
#endif
{
NEED_IP(t + 3);
NEED_OP(t);
while (t > 0) {
*op++ = *ip++;
t--;
}
}
}
eof_found:
*out_len = op - out;
return (t != 3 ? LZO_E_ERROR :
ip == ip_end ? LZO_E_OK :
ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN);
input_overrun:
*out_len = op - out;
return LZO_E_INPUT_OVERRUN;
output_overrun:
*out_len = op - out;
return LZO_E_OUTPUT_OVERRUN;
lookbehind_overrun:
*out_len = op - out;
return LZO_E_LOOKBEHIND_OVERRUN;
}
Commit Message: lzo: properly check for overruns
The lzo decompressor can, if given some really crazy data, possibly
overrun some variable types. Modify the checking logic to properly
detect overruns before they happen.
Reported-by: "Don A. Bailey" <[email protected]>
Tested-by: "Don A. Bailey" <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: Ins_FLIPPT( INS_ARG )
{
FT_UShort point;
FT_UNUSED_ARG;
if ( CUR.top < CUR.GS.loop )
{
CUR.error = TT_Err_Too_Few_Arguments;
return;
}
while ( CUR.GS.loop > 0 )
{
CUR.args--;
point = (FT_UShort)CUR.stack[CUR.args];
if ( BOUNDS( point, CUR.pts.n_points ) )
{
if ( CUR.pedantic_hinting )
{
CUR.error = TT_Err_Invalid_Reference;
return;
}
}
else
CUR.pts.tags[point] ^= FT_CURVE_TAG_ON;
CUR.GS.loop--;
}
CUR.GS.loop = 1;
CUR.new_top = CUR.args;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8TestObject::OverloadedMethodHMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_overloadedMethodH");
test_object_v8_internal::OverloadedMethodHMethod(info);
}
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:
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 ContextImpl::CreateFrame(
fidl::InterfaceHandle<chromium::web::FrameObserver> observer,
fidl::InterfaceRequest<chromium::web::Frame> frame_request) {
auto web_contents = content::WebContents::Create(
content::WebContents::CreateParams(browser_context_, nullptr));
frame_bindings_.AddBinding(
std::make_unique<FrameImpl>(std::move(web_contents), observer.Bind()),
std::move(frame_request));
}
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: static MediaContainerName LookupContainerByFirst4(const uint8* buffer,
int buffer_size) {
if (buffer_size < 12)
return CONTAINER_UNKNOWN;
uint32 first4 = Read32(buffer);
switch (first4) {
case 0x1a45dfa3:
if (CheckWebm(buffer, buffer_size))
return CONTAINER_WEBM;
break;
case 0x3026b275:
if (StartsWith(buffer,
buffer_size,
kAsfSignature,
sizeof(kAsfSignature))) {
return CONTAINER_ASF;
}
break;
case TAG('#','!','A','M'):
if (StartsWith(buffer, buffer_size, kAmrSignature))
return CONTAINER_AMR;
break;
case TAG('#','E','X','T'):
if (CheckHls(buffer, buffer_size))
return CONTAINER_HLS;
break;
case TAG('.','R','M','F'):
if (buffer[4] == 0 && buffer[5] == 0)
return CONTAINER_RM;
break;
case TAG('.','r','a','\xfd'):
return CONTAINER_RM;
case TAG('B','I','K','b'):
case TAG('B','I','K','d'):
case TAG('B','I','K','f'):
case TAG('B','I','K','g'):
case TAG('B','I','K','h'):
case TAG('B','I','K','i'):
if (CheckBink(buffer, buffer_size))
return CONTAINER_BINK;
break;
case TAG('c','a','f','f'):
if (CheckCaf(buffer, buffer_size))
return CONTAINER_CAF;
break;
case TAG('D','E','X','A'):
if (buffer_size > 15 &&
Read16(buffer + 11) <= 2048 &&
Read16(buffer + 13) <= 2048) {
return CONTAINER_DXA;
}
break;
case TAG('D','T','S','H'):
if (Read32(buffer + 4) == TAG('D','H','D','R'))
return CONTAINER_DTSHD;
break;
case 0x64a30100:
case 0x64a30200:
case 0x64a30300:
case 0x64a30400:
case 0x0001a364:
case 0x0002a364:
case 0x0003a364:
if (Read32(buffer + 4) != 0 && Read32(buffer + 8) != 0)
return CONTAINER_IRCAM;
break;
case TAG('f','L','a','C'):
return CONTAINER_FLAC;
case TAG('F','L','V',0):
case TAG('F','L','V',1):
case TAG('F','L','V',2):
case TAG('F','L','V',3):
case TAG('F','L','V',4):
if (buffer[5] == 0 && Read32(buffer + 5) > 8)
return CONTAINER_FLV;
break;
case TAG('F','O','R','M'):
switch (Read32(buffer + 8)) {
case TAG('A','I','F','F'):
case TAG('A','I','F','C'):
return CONTAINER_AIFF;
}
break;
case TAG('M','A','C',' '):
return CONTAINER_APE;
case TAG('O','N','2',' '):
if (Read32(buffer + 8) == TAG('O','N','2','f'))
return CONTAINER_AVI;
break;
case TAG('O','g','g','S'):
if (buffer[5] <= 7)
return CONTAINER_OGG;
break;
case TAG('R','F','6','4'):
if (buffer_size > 16 && Read32(buffer + 12) == TAG('d','s','6','4'))
return CONTAINER_WAV;
break;
case TAG('R','I','F','F'):
switch (Read32(buffer + 8)) {
case TAG('A','V','I',' '):
case TAG('A','V','I','X'):
case TAG('A','V','I','\x19'):
case TAG('A','M','V',' '):
return CONTAINER_AVI;
case TAG('W','A','V','E'):
return CONTAINER_WAV;
}
break;
case TAG('[','S','c','r'):
if (StartsWith(buffer, buffer_size, kAssSignature))
return CONTAINER_ASS;
break;
case TAG('\xef','\xbb','\xbf','['):
if (StartsWith(buffer, buffer_size, kAssBomSignature))
return CONTAINER_ASS;
break;
case 0x7ffe8001:
case 0xfe7f0180:
case 0x1fffe800:
case 0xff1f00e8:
if (CheckDts(buffer, buffer_size))
return CONTAINER_DTS;
break;
case 0xb7d80020:
if (StartsWith(buffer,
buffer_size,
kWtvSignature,
sizeof(kWtvSignature))) {
return CONTAINER_WTV;
}
break;
}
uint32 first3 = first4 & 0xffffff00;
switch (first3) {
case TAG('C','W','S',0):
case TAG('F','W','S',0):
return CONTAINER_SWF;
case TAG('I','D','3',0):
if (CheckMp3(buffer, buffer_size, true))
return CONTAINER_MP3;
break;
}
uint32 first2 = Read16(buffer);
switch (first2) {
case kAc3SyncWord:
if (CheckAc3(buffer, buffer_size))
return CONTAINER_AC3;
if (CheckEac3(buffer, buffer_size))
return CONTAINER_EAC3;
break;
case 0xfff0:
case 0xfff1:
case 0xfff8:
case 0xfff9:
if (CheckAac(buffer, buffer_size))
return CONTAINER_AAC;
break;
}
if (CheckMp3(buffer, buffer_size, false))
return CONTAINER_MP3;
return CONTAINER_UNKNOWN;
}
Commit Message: Add extra checks to avoid integer overflow.
BUG=425980
TEST=no crash with ASAN
Review URL: https://codereview.chromium.org/659743004
Cr-Commit-Position: refs/heads/master@{#301249}
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ZIPARCHIVE_METHOD(unchangeAll)
{
struct zip *intern;
zval *self = getThis();
if (!self) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, self);
if (zip_unchange_all(intern) != 0) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom*
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: xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style,
const xmlChar *name, const xmlChar *ns,
ATTRIBUTE_UNUSED const xmlChar *ignored) {
xsltAttrElemPtr tmp;
xsltAttrElemPtr refs;
tmp = values;
while (tmp != NULL) {
if (tmp->set != NULL) {
/*
* Check against cycles !
*/
if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets recursion detected on %s\n",
name);
} else {
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"Importing attribute list %s\n", tmp->set);
#endif
refs = xsltGetSAS(style, tmp->set, tmp->ns);
if (refs == NULL) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets %s reference missing %s\n",
name, tmp->set);
} else {
/*
* recurse first for cleanup
*/
xsltResolveSASCallback(refs, style, name, ns, NULL);
/*
* Then merge
*/
xsltMergeAttrElemList(style, values, refs);
/*
* Then suppress the reference
*/
tmp->set = NULL;
tmp->ns = NULL;
}
}
}
tmp = tmp->next;
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void QQuickWebViewExperimental::setAuthenticationDialog(QDeclarativeComponent* authenticationDialog)
{
Q_D(QQuickWebView);
if (d->authenticationDialog == authenticationDialog)
return;
d->authenticationDialog = authenticationDialog;
emit authenticationDialogChanged();
}
Commit Message: [Qt][WK2] Allow transparent WebViews
https://bugs.webkit.org/show_bug.cgi?id=80608
Reviewed by Tor Arne Vestbø.
Added support for transparentBackground in QQuickWebViewExperimental.
This uses the existing drawsTransparentBackground property in WebKit2.
Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes,
otherwise the change doesn't take effect.
A new API test was added.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::setTransparentBackground):
(QQuickWebViewPrivate::transparentBackground):
(QQuickWebViewExperimental::transparentBackground):
(QQuickWebViewExperimental::setTransparentBackground):
* UIProcess/API/qt/qquickwebview_p.h:
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
* UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp:
(tst_QQuickWebView):
(tst_QQuickWebView::transparentWebViews):
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::LayerTreeHostQt::LayerTreeHostQt):
(WebKit::LayerTreeHostQt::setRootCompositingLayer):
git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BluetoothOptionsHandler::GenerateFakeDeviceList() {
GenerateFakeDiscoveredDevice(
"Fake Wireless Keyboard",
"01-02-03-04-05-06",
"input-keyboard",
true,
true);
GenerateFakeDiscoveredDevice(
"Fake Wireless Mouse",
"02-03-04-05-06-01",
"input-mouse",
true,
false);
GenerateFakeDiscoveredDevice(
"Fake Wireless Headset",
"03-04-05-06-01-02",
"headset",
false,
false);
GenerateFakePairing(
"Fake Connecting Keyboard",
"04-05-06-01-02-03",
"input-keyboard",
"bluetoothRemotePasskey");
GenerateFakePairing(
"Fake Connecting Phone",
"05-06-01-02-03-04",
"phone",
"bluetoothConfirmPasskey");
GenerateFakePairing(
"Fake Connecting Headset",
"06-01-02-03-04-05",
"headset",
"bluetoothEnterPasskey");
web_ui_->CallJavascriptFunction(
"options.SystemOptions.notifyBluetoothSearchComplete");
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CameraSource::signalBufferReturned(MediaBuffer *buffer) {
ALOGV("signalBufferReturned: %p", buffer->data());
Mutex::Autolock autoLock(mLock);
for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin();
it != mFramesBeingEncoded.end(); ++it) {
if ((*it)->pointer() == buffer->data()) {
releaseOneRecordingFrame((*it));
mFramesBeingEncoded.erase(it);
++mNumFramesEncoded;
buffer->setObserver(0);
buffer->release();
mFrameCompleteCondition.signal();
return;
}
}
CHECK(!"signalBufferReturned: bogus buffer");
}
Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak
Subtract address of a random static object from pointers being routed
through app process.
Bug: 28466701
Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04
CWE ID: CWE-200
Target: 1
Example 2:
Code: aura::Window* CreateWindowWithWidget(const gfx::Rect& bounds) {
views::Widget* widget = new views::Widget();
views::Widget::InitParams params;
params.context = CurrentContext();
widget->Init(params);
widget->Show();
aura::Window* window = widget->GetNativeWindow();
window->SetBounds(bounds);
window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL);
return window;
}
Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash
For the ones that fail, disable them via filter file instead of in the
code, per our disablement policy.
Bug: 698085, 695556, 698878, 698888, 698093, 698894
Test: ash_unittests --mash
Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26
Reviewed-on: https://chromium-review.googlesource.com/752423
Commit-Queue: James Cook <[email protected]>
Reviewed-by: Steven Bennetts <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513836}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: e1000e_intrmgr_pause(E1000ECore *core)
{
int i;
e1000e_intmgr_timer_pause(&core->radv);
e1000e_intmgr_timer_pause(&core->rdtr);
e1000e_intmgr_timer_pause(&core->raid);
e1000e_intmgr_timer_pause(&core->tidv);
e1000e_intmgr_timer_pause(&core->tadv);
e1000e_intmgr_timer_pause(&core->itr);
for (i = 0; i < E1000E_MSIX_VEC_NUM; i++) {
e1000e_intmgr_timer_pause(&core->eitr[i]);
}
}
Commit Message:
CWE ID: CWE-835
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FormAssociatedElement::formRemovedFromTree(const Node* formRoot)
{
ASSERT(m_form);
if (toHTMLElement(this)->highestAncestor() != formRoot)
setForm(0);
}
Commit Message: Fix a crash when a form control is in a past naems map of a demoted form element.
Note that we wanted to add the protector in FormAssociatedElement::setForm(),
but we couldn't do it because it is called from the constructor.
BUG=326854
TEST=automated.
Review URL: https://codereview.chromium.org/105693013
git-svn-id: svn://svn.chromium.org/blink/trunk@163680 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-287
Target: 1
Example 2:
Code: static int vmci_transport_notify_send_post_enqueue(
struct vsock_sock *vsk,
ssize_t written,
struct vsock_transport_send_notify_data *data)
{
return vmci_trans(vsk)->notify_ops->send_post_enqueue(
&vsk->sk, written,
(struct vmci_transport_send_notify_data *)data);
}
Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue()
In case we received no data on the call to skb_recv_datagram(), i.e.
skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0
without updating msg_namelen leading to net/socket.c leaking the local,
uninitialized sockaddr_storage variable to userland -- 128 bytes of
kernel stack memory.
Fix this by moving the already existing msg_namelen assignment a few
lines above.
Cc: Andy King <[email protected]>
Cc: Dmitry Torokhov <[email protected]>
Cc: George Zhang <[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: static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
Commit Message: fix "pixel overrun"
fixes #3
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 __init is_skylake_era(void)
{
if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL &&
boot_cpu_data.x86 == 6) {
switch (boot_cpu_data.x86_model) {
case INTEL_FAM6_SKYLAKE_MOBILE:
case INTEL_FAM6_SKYLAKE_DESKTOP:
case INTEL_FAM6_SKYLAKE_X:
case INTEL_FAM6_KABYLAKE_MOBILE:
case INTEL_FAM6_KABYLAKE_DESKTOP:
return true;
}
}
return false;
}
Commit Message: x86/speculation: Protect against userspace-userspace spectreRSB
The article "Spectre Returns! Speculation Attacks using the Return Stack
Buffer" [1] describes two new (sub-)variants of spectrev2-like attacks,
making use solely of the RSB contents even on CPUs that don't fallback to
BTB on RSB underflow (Skylake+).
Mitigate userspace-userspace attacks by always unconditionally filling RSB on
context switch when the generic spectrev2 mitigation has been enabled.
[1] https://arxiv.org/pdf/1807.07940.pdf
Signed-off-by: Jiri Kosina <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Reviewed-by: Josh Poimboeuf <[email protected]>
Acked-by: Tim Chen <[email protected]>
Cc: Konrad Rzeszutek Wilk <[email protected]>
Cc: Borislav Petkov <[email protected]>
Cc: David Woodhouse <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: [email protected]
Link: https://lkml.kernel.org/r/[email protected]
CWE ID:
Target: 1
Example 2:
Code: static enum hrtimer_restart pit_timer_fn(struct hrtimer *data)
{
struct kvm_kpit_state *ps = container_of(data, struct kvm_kpit_state, timer);
struct kvm_pit *pt = ps->kvm->arch.vpit;
if (ps->reinject || !atomic_read(&ps->pending)) {
atomic_inc(&ps->pending);
queue_kthread_work(&pt->worker, &pt->expired);
}
if (ps->is_periodic) {
hrtimer_add_expires_ns(&ps->timer, ps->period);
return HRTIMER_RESTART;
} else
return HRTIMER_NORESTART;
}
Commit Message: KVM: x86: Improve thread safety in pit
There's a race condition in the PIT emulation code in KVM. In
__kvm_migrate_pit_timer the pit_timer object is accessed without
synchronization. If the race condition occurs at the wrong time this
can crash the host kernel.
This fixes CVE-2014-3611.
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[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: saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
{
#ifdef _DEBUG
xmltooling::NDC("resolve");
#endif
Category& log=Category::getInstance(SHIBSP_LOGCAT ".MetadataProvider.Dynamic");
string name;
if (criteria.entityID_ascii) {
name = criteria.entityID_ascii;
}
else if (criteria.entityID_unicode) {
auto_ptr_char temp(criteria.entityID_unicode);
name = temp.get();
}
else if (criteria.artifact) {
if (m_subst.empty() && (m_regex.empty() || m_match.empty()))
throw saml2md::MetadataException("Unable to resolve metadata dynamically from an artifact.");
name = "{sha1}" + criteria.artifact->getSource();
}
if (!m_subst.empty()) {
string name2(name);
if (!m_hashed.empty()) {
name2 = SecurityHelper::doHash(m_hashed.c_str(), name.c_str(), name.length());
}
name2 = boost::replace_first_copy(m_subst, "$entityID",
m_encoded ? XMLToolingConfig::getConfig().getURLEncoder()->encode(name2.c_str()) : name2);
log.info("transformed location from (%s) to (%s)", name.c_str(), name2.c_str());
name = name2;
}
else if (!m_match.empty() && !m_regex.empty()) {
try {
RegularExpression exp(m_match.c_str());
XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
if (temp) {
auto_ptr_char narrow(temp);
XMLString::release(&temp);
if (name != narrow.get()) {
log.info("transformed location from (%s) to (%s)", name.c_str(), narrow.get());
name = narrow.get();
}
}
}
catch (XMLException& ex) {
auto_ptr_char msg(ex.getMessage());
log.error("caught error applying regular expression: %s", msg.get());
}
}
if (XMLString::startsWithI(name.c_str(), "file://")) {
MetadataProvider::Criteria baseCriteria(name.c_str());
return saml2md::DynamicMetadataProvider::resolve(baseCriteria);
}
const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
if (!mpc)
throw saml2md::MetadataException("Dynamic MetadataProvider requires Shibboleth-aware lookup criteria, check calling code.");
const PropertySet* relyingParty;
if (criteria.artifact)
relyingParty = mpc->application.getRelyingParty((XMLCh*)nullptr);
else if (criteria.entityID_unicode)
relyingParty = mpc->application.getRelyingParty(criteria.entityID_unicode);
else {
auto_ptr_XMLCh temp2(name.c_str());
relyingParty = mpc->application.getRelyingParty(temp2.get());
}
SOAPTransport::Address addr(relyingParty->getString("entityID").second, name.c_str(), name.c_str());
const char* pch = strchr(addr.m_endpoint,':');
if (!pch)
throw IOException("location was not a URL.");
string scheme(addr.m_endpoint, pch-addr.m_endpoint);
boost::scoped_ptr<SOAPTransport> transport;
try {
transport.reset(XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr));
}
catch (exception& ex) {
log.error("exception while building transport object to resolve URL: %s", ex.what());
throw IOException("Unable to resolve entityID with a known transport protocol.");
}
transport->setVerifyHost(m_verifyHost);
if (m_trust.get() && m_dummyCR.get() && !transport->setTrustEngine(m_trust.get(), m_dummyCR.get()))
throw IOException("Unable to install X509TrustEngine into transport object.");
Locker credlocker(nullptr, false);
CredentialResolver* credResolver = nullptr;
pair<bool,const char*> authType=relyingParty->getString("authType");
if (!authType.first || !strcmp(authType.second,"TLS")) {
credResolver = mpc->application.getCredentialResolver();
if (credResolver)
credlocker.assign(credResolver);
if (credResolver) {
CredentialCriteria cc;
cc.setUsage(Credential::TLS_CREDENTIAL);
authType = relyingParty->getString("keyName");
if (authType.first)
cc.getKeyNames().insert(authType.second);
const Credential* cred = credResolver->resolve(&cc);
cc.getKeyNames().clear();
if (cred) {
if (!transport->setCredential(cred))
log.error("failed to load Credential into metadata resolver");
}
else {
log.error("no TLS credential supplied");
}
}
else {
log.error("no CredentialResolver available for TLS");
}
}
else {
SOAPTransport::transport_auth_t type=SOAPTransport::transport_auth_none;
pair<bool,const char*> username=relyingParty->getString("authUsername");
pair<bool,const char*> password=relyingParty->getString("authPassword");
if (!username.first || !password.first)
log.error("transport authType (%s) specified but authUsername or authPassword was missing", authType.second);
else if (!strcmp(authType.second,"basic"))
type = SOAPTransport::transport_auth_basic;
else if (!strcmp(authType.second,"digest"))
type = SOAPTransport::transport_auth_digest;
else if (!strcmp(authType.second,"ntlm"))
type = SOAPTransport::transport_auth_ntlm;
else if (!strcmp(authType.second,"gss"))
type = SOAPTransport::transport_auth_gss;
else if (strcmp(authType.second,"none"))
log.error("unknown authType (%s) specified for RelyingParty", authType.second);
if (type > SOAPTransport::transport_auth_none) {
if (transport->setAuth(type,username.second,password.second))
log.debug("configured for transport authentication (method=%s, username=%s)", authType.second, username.second);
else
log.error("failed to configure transport authentication (method=%s)", authType.second);
}
}
pair<bool,unsigned int> timeout = relyingParty->getUnsignedInt("connectTimeout");
transport->setConnectTimeout(timeout.first ? timeout.second : 10);
timeout = relyingParty->getUnsignedInt("timeout");
transport->setTimeout(timeout.first ? timeout.second : 20);
mpc->application.getServiceProvider().setTransportOptions(*transport);
HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport.get());
if (http) {
pair<bool,bool> flag = relyingParty->getBool("chunkedEncoding");
http->useChunkedEncoding(flag.first && flag.second);
http->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT);
http->setRequestHeader("XML-Security-C", XSEC_FULLVERSIONDOT);
http->setRequestHeader("OpenSAML-C", gOpenSAMLDotVersionStr);
http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
}
try {
transport->send();
istream& msg = transport->receive();
DOMDocument* doc=nullptr;
StreamInputSource src(msg, "DynamicMetadataProvider");
Wrapper4InputSource dsrc(&src,false);
if (m_validate)
doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
else
doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
XercesJanitor<DOMDocument> docjanitor(doc);
if (!doc->getDocumentElement() || !XMLHelper::isNodeNamed(doc->getDocumentElement(),
samlconstants::SAML20MD_NS, saml2md::EntityDescriptor::LOCAL_NAME)) {
throw saml2md::MetadataException("Root of metadata instance was not an EntityDescriptor");
}
auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
docjanitor.release();
saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
if (!entity) {
throw saml2md::MetadataException(
"Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
);
}
xmlObject.release();
return entity;
}
catch (XMLException& e) {
auto_ptr_char msg(e.getMessage());
log.error("Xerces error while resolving location (%s): %s", name.c_str(), msg.get());
throw saml2md::MetadataException(msg.get());
}
}
Commit Message:
CWE ID: CWE-347
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: make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo,
int PNG_CONST bdhi)
{
for (; bdlo <= bdhi; ++bdlo)
{
png_uint_32 width;
for (width = 1; width <= 16; ++width)
{
png_uint_32 height;
for (height = 1; height <= 16; ++height)
{
/* The four combinations of DIY interlace and interlace or not -
* no interlace + DIY should be identical to no interlace with
* libpng doing it.
*/
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 0);
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 1);
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 0);
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 1);
# endif
}
}
}
}
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: WebMediaPlayer::Preload HTMLMediaElement::effectivePreloadType() const {
if (autoplay() && !isGestureNeededForPlayback())
return WebMediaPlayer::PreloadAuto;
WebMediaPlayer::Preload preload = preloadType();
if (m_ignorePreloadNone && preload == WebMediaPlayer::PreloadNone)
return WebMediaPlayer::PreloadMetaData;
return preload;
}
Commit Message: [Blink>Media] Allow autoplay muted on Android by default
There was a mistake causing autoplay muted is shipped on Android
but it will be disabled if the chromium embedder doesn't specify
content setting for "AllowAutoplay" preference. This CL makes the
AllowAutoplay preference true by default so that it is allowed by
embedders (including AndroidWebView) unless they explicitly
disable it.
Intent to ship:
https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ
BUG=689018
Review-Url: https://codereview.chromium.org/2677173002
Cr-Commit-Position: refs/heads/master@{#448423}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 DebuggerFunction::InitAgentHost() {
if (debuggee_.tab_id) {
WebContents* web_contents = NULL;
bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id,
GetProfile(),
include_incognito(),
NULL,
NULL,
&web_contents,
NULL);
if (result && web_contents) {
GURL url = web_contents->GetVisibleURL();
if (PermissionsData::IsRestrictedUrl(url, extension(), &error_))
return false;
agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents);
}
} else if (debuggee_.extension_id) {
ExtensionHost* extension_host =
ProcessManager::Get(GetProfile())
->GetBackgroundHostForExtension(*debuggee_.extension_id);
if (extension_host) {
if (PermissionsData::IsRestrictedUrl(extension_host->GetURL(),
extension(),
&error_)) {
return false;
}
agent_host_ =
DevToolsAgentHost::GetOrCreateFor(extension_host->host_contents());
}
} else if (debuggee_.target_id) {
agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id);
if (agent_host_.get()) {
if (PermissionsData::IsRestrictedUrl(agent_host_->GetURL(),
extension(),
&error_)) {
agent_host_ = nullptr;
return false;
}
}
} else {
error_ = keys::kInvalidTargetError;
return false;
}
if (!agent_host_.get()) {
FormatErrorMessage(keys::kNoTargetError);
return false;
}
return true;
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
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 long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages)
{
struct pipe_buffer *bufs;
/*
* We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't
* expect a lot of shrink+grow operations, just free and allocate
* again like we would do for growing. If the pipe currently
* contains more buffers than arg, then return busy.
*/
if (nr_pages < pipe->nrbufs)
return -EBUSY;
bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN);
if (unlikely(!bufs))
return -ENOMEM;
/*
* The pipe array wraps around, so just start the new one at zero
* and adjust the indexes.
*/
if (pipe->nrbufs) {
unsigned int tail;
unsigned int head;
tail = pipe->curbuf + pipe->nrbufs;
if (tail < pipe->buffers)
tail = 0;
else
tail &= (pipe->buffers - 1);
head = pipe->nrbufs - tail;
if (head)
memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer));
if (tail)
memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer));
}
pipe->curbuf = 0;
kfree(pipe->bufs);
pipe->bufs = bufs;
pipe->buffers = nr_pages;
return nr_pages * PAGE_SIZE;
}
Commit Message: pipe: limit the per-user amount of pages allocated in pipes
On no-so-small systems, it is possible for a single process to cause an
OOM condition by filling large pipes with data that are never read. A
typical process filling 4000 pipes with 1 MB of data will use 4 GB of
memory. On small systems it may be tricky to set the pipe max size to
prevent this from happening.
This patch makes it possible to enforce a per-user soft limit above
which new pipes will be limited to a single page, effectively limiting
them to 4 kB each, as well as a hard limit above which no new pipes may
be created for this user. This has the effect of protecting the system
against memory abuse without hurting other users, and still allowing
pipes to work correctly though with less data at once.
The limit are controlled by two new sysctls : pipe-user-pages-soft, and
pipe-user-pages-hard. Both may be disabled by setting them to zero. The
default soft limit allows the default number of FDs per process (1024)
to create pipes of the default size (64kB), thus reaching a limit of 64MB
before starting to create only smaller pipes. With 256 processes limited
to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB =
1084 MB of memory allocated for a user. The hard limit is disabled by
default to avoid breaking existing applications that make intensive use
of pipes (eg: for splicing).
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: base::string16 ExtensionInstallPrompt::Prompt::GetAcceptButtonLabel() const {
int id = kAcceptButtonIds[type_];
if (type_ == INSTALL_PROMPT || type_ == INLINE_INSTALL_PROMPT ||
type_ == DELEGATED_PERMISSIONS_PROMPT) {
if (extension_->is_app())
id = IDS_EXTENSION_INSTALL_PROMPT_ACCEPT_BUTTON_APP;
else if (extension_->is_theme())
id = IDS_EXTENSION_INSTALL_PROMPT_ACCEPT_BUTTON_THEME;
else
id = IDS_EXTENSION_INSTALL_PROMPT_ACCEPT_BUTTON_EXTENSION;
} else if (type_ == EXTERNAL_INSTALL_PROMPT) {
if (extension_->is_app())
id = IDS_EXTENSION_EXTERNAL_INSTALL_PROMPT_ACCEPT_BUTTON_APP;
else if (extension_->is_theme())
id = IDS_EXTENSION_EXTERNAL_INSTALL_PROMPT_ACCEPT_BUTTON_THEME;
else
id = IDS_EXTENSION_EXTERNAL_INSTALL_PROMPT_ACCEPT_BUTTON_EXTENSION;
} else if (type_ == POST_INSTALL_PERMISSIONS_PROMPT) {
if (GetRetainedFileCount() && GetRetainedDeviceCount()) {
id =
IDS_EXTENSION_PROMPT_PERMISSIONS_CLEAR_RETAINED_FILES_AND_DEVICES_BUTTON;
} else if (GetRetainedFileCount()) {
id = IDS_EXTENSION_PROMPT_PERMISSIONS_CLEAR_RETAINED_FILES_BUTTON;
} else if (GetRetainedDeviceCount()) {
id = IDS_EXTENSION_PROMPT_PERMISSIONS_CLEAR_RETAINED_DEVICES_BUTTON;
}
} else if (type_ == REMOTE_INSTALL_PROMPT) {
if (extension_->is_app())
id = IDS_EXTENSION_PROMPT_REMOTE_INSTALL_BUTTON_APP;
else
id = IDS_EXTENSION_PROMPT_REMOTE_INSTALL_BUTTON_EXTENSION;
} else if (type_ == REPAIR_PROMPT) {
if (extension_->is_app())
id = IDS_EXTENSION_PROMPT_REPAIR_BUTTON_APP;
else
id = IDS_EXTENSION_PROMPT_REPAIR_BUTTON_EXTENSION;
}
return id ? l10n_util::GetStringUTF16(id) : base::string16();
}
Commit Message: Make the webstore inline install dialog be tab-modal
Also clean up a few minor lint errors while I'm in here.
BUG=550047
Review URL: https://codereview.chromium.org/1496033003
Cr-Commit-Position: refs/heads/master@{#363925}
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: process_text2(STREAM s, TEXT2_ORDER * os, uint32 present, RD_BOOL delta)
{
UNUSED(delta);
BRUSH brush;
if (present & 0x000001)
in_uint8(s, os->font);
if (present & 0x000002)
in_uint8(s, os->flags);
if (present & 0x000004)
in_uint8(s, os->opcode);
if (present & 0x000008)
in_uint8(s, os->mixmode);
if (present & 0x000010)
rdp_in_colour(s, &os->fgcolour);
if (present & 0x000020)
rdp_in_colour(s, &os->bgcolour);
if (present & 0x000040)
in_uint16_le(s, os->clipleft);
if (present & 0x000080)
in_uint16_le(s, os->cliptop);
if (present & 0x000100)
in_uint16_le(s, os->clipright);
if (present & 0x000200)
in_uint16_le(s, os->clipbottom);
if (present & 0x000400)
in_uint16_le(s, os->boxleft);
if (present & 0x000800)
in_uint16_le(s, os->boxtop);
if (present & 0x001000)
in_uint16_le(s, os->boxright);
if (present & 0x002000)
in_uint16_le(s, os->boxbottom);
rdp_parse_brush(s, &os->brush, present >> 14);
if (present & 0x080000)
in_uint16_le(s, os->x);
if (present & 0x100000)
in_uint16_le(s, os->y);
if (present & 0x200000)
{
in_uint8(s, os->length);
in_uint8a(s, os->text, os->length);
}
logger(Graphics, Debug,
"process_text2(), x=%d, y=%d, cl=%d, ct=%d, cr=%d, cb=%d, bl=%d, bt=%d, br=%d, bb=%d, bs=%d, bg=0x%x, fg=0x%x, font=%d, fl=0x%x, op=0x%x, mix=%d, n=%d",
os->x, os->y, os->clipleft, os->cliptop, os->clipright, os->clipbottom, os->boxleft,
os->boxtop, os->boxright, os->boxbottom, os->brush.style, os->bgcolour, os->fgcolour,
os->font, os->flags, os->opcode, os->mixmode, os->length);
setup_brush(&brush, &os->brush);
ui_draw_text(os->font, os->flags, os->opcode - 1, os->mixmode, os->x, os->y,
os->clipleft, os->cliptop, os->clipright - os->clipleft,
os->clipbottom - os->cliptop, os->boxleft, os->boxtop,
os->boxright - os->boxleft, os->boxbottom - os->boxtop,
&brush, os->bgcolour, os->fgcolour, os->text, os->length);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
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: bool CreateIpcChannel(
const std::string& channel_name,
const std::string& pipe_security_descriptor,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
IPC::Listener* delegate,
scoped_ptr<IPC::ChannelProxy>* channel_out) {
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(security_attributes);
security_attributes.bInheritHandle = FALSE;
ULONG security_descriptor_length = 0;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
UTF8ToUTF16(pipe_security_descriptor).c_str(),
SDDL_REVISION_1,
reinterpret_cast<PSECURITY_DESCRIPTOR*>(
&security_attributes.lpSecurityDescriptor),
&security_descriptor_length)) {
LOG_GETLASTERROR(ERROR) <<
"Failed to create a security descriptor for the Chromoting IPC channel";
return false;
}
std::string pipe_name(kChromePipeNamePrefix);
pipe_name.append(channel_name);
base::win::ScopedHandle pipe;
pipe.Set(CreateNamedPipe(
UTF8ToUTF16(pipe_name).c_str(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
1,
IPC::Channel::kReadBufferSize,
IPC::Channel::kReadBufferSize,
5000,
&security_attributes));
if (!pipe.IsValid()) {
LOG_GETLASTERROR(ERROR) <<
"Failed to create the server end of the Chromoting IPC channel";
LocalFree(security_attributes.lpSecurityDescriptor);
return false;
}
LocalFree(security_attributes.lpSecurityDescriptor);
channel_out->reset(new IPC::ChannelProxy(
IPC::ChannelHandle(pipe),
IPC::Channel::MODE_SERVER,
delegate,
io_task_runner));
return true;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void GlobalConfirmInfoBar::Close() {
delete this;
}
Commit Message: Allow to specify elide behavior for confrim infobar message
Used in "<extension name> is debugging this browser" infobar.
Bug: 823194
Change-Id: Iff6627097c020cccca8f7cc3e21a803a41fd8f2c
Reviewed-on: https://chromium-review.googlesource.com/1048064
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557245}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const char* Chapters::Display::GetLanguage() const
{
return m_language;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ReadPSDLayersInternal(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
if (length > GetBlobSize(image))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"InsufficientImageDataInFile",image->filename);
}
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/714
CWE ID: CWE-834
Target: 1
Example 2:
Code: void RenderWidgetHostImpl::ForwardKeyboardEvent(
const NativeWebKeyboardEvent& key_event) {
TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
if (owner_delegate_ &&
!owner_delegate_->MayRenderWidgetForwardKeyboardEvent(key_event)) {
return;
}
if (ShouldDropInputEvents())
return;
if (!process_->HasConnection())
return;
if (KeyPressListenersHandleEvent(key_event)) {
if (key_event.type == WebKeyboardEvent::RawKeyDown)
suppress_next_char_events_ = true;
return;
}
if (!WebInputEvent::isKeyboardEventType(key_event.type))
return;
if (suppress_next_char_events_) {
if (key_event.type == WebKeyboardEvent::Char)
return;
suppress_next_char_events_ = false;
}
bool is_shortcut = false;
if (delegate_ && !key_event.skip_in_browser) {
if (key_event.type == WebKeyboardEvent::RawKeyDown)
suppress_next_char_events_ = true;
if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
return;
if (key_event.type == WebKeyboardEvent::RawKeyDown)
suppress_next_char_events_ = false;
}
if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
return;
NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event);
key_event_with_latency.event.isBrowserShortcut = is_shortcut;
latency_tracker_.OnInputEvent(key_event, &key_event_with_latency.latency);
input_router_->SendKeyboardEvent(key_event_with_latency);
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
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: xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) {
int i = 0;
int j = comp->nbStep - 1;
while (j > i) {
register xmlChar *tmp;
register xsltOp op;
register xmlXPathCompExprPtr expr;
register int t;
tmp = comp->steps[i].value;
comp->steps[i].value = comp->steps[j].value;
comp->steps[j].value = tmp;
tmp = comp->steps[i].value2;
comp->steps[i].value2 = comp->steps[j].value2;
comp->steps[j].value2 = tmp;
tmp = comp->steps[i].value3;
comp->steps[i].value3 = comp->steps[j].value3;
comp->steps[j].value3 = tmp;
op = comp->steps[i].op;
comp->steps[i].op = comp->steps[j].op;
comp->steps[j].op = op;
expr = comp->steps[i].comp;
comp->steps[i].comp = comp->steps[j].comp;
comp->steps[j].comp = expr;
t = comp->steps[i].previousExtra;
comp->steps[i].previousExtra = comp->steps[j].previousExtra;
comp->steps[j].previousExtra = t;
t = comp->steps[i].indexExtra;
comp->steps[i].indexExtra = comp->steps[j].indexExtra;
comp->steps[j].indexExtra = t;
t = comp->steps[i].lenExtra;
comp->steps[i].lenExtra = comp->steps[j].lenExtra;
comp->steps[j].lenExtra = t;
j--;
i++;
}
xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0);
/*
* detect consecutive XSLT_OP_PREDICATE indicating a direct
* matching should be done.
*/
for (i = 0;i < comp->nbStep - 1;i++) {
if ((comp->steps[i].op == XSLT_OP_PREDICATE) &&
(comp->steps[i + 1].op == XSLT_OP_PREDICATE)) {
comp->direct = 1;
if (comp->pattern[0] != '/') {
xmlChar *query;
query = xmlStrdup((const xmlChar *)"//");
query = xmlStrcat(query, comp->pattern);
xmlFree((xmlChar *) comp->pattern);
comp->pattern = query;
}
break;
}
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, **pubkey, *sealdata, *ekeys;
HashTable *pubkeysht;
HashPosition pos;
EVP_PKEY **pkeys;
long * key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys;
unsigned char *buf = NULL, **eks;
char * data; int data_len;
char *method =NULL;
int method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
return;
}
pubkeysht = HASH_OF(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
if (EVP_CIPHER_iv_length(cipher) > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ciphers with modes requiring IV are not supported");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(long), 0);
memset(key_resources, 0, sizeof(*key_resources) * nkeys);
/* get the public keys we are using to seal this data */
zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
i = 0;
while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
&pos) == SUCCESS) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
if (pkeys[i] == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
zend_hash_move_forward_ex(pubkeysht, &pos);
i++;
}
if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
RETVAL_FALSE;
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
#if 0
/* Need this if allow ciphers that require initialization vector */
ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
iv = ivlen ? emalloc(ivlen + 1) : NULL;
#endif
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
EVP_CIPHER_CTX_cleanup(&ctx);
if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
EVP_SealFinal(&ctx, buf + len1, &len2);
if (len1 + len2 > 0) {
zval_dtor(sealdata);
buf[len1 + len2] = '\0';
buf = erealloc(buf, len1 + len2 + 1);
ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
eks[i] = NULL;
}
#if 0
/* If allow ciphers that need IV, we need this */
zval_dtor(*ivec);
if (ivlen) {
iv[ivlen] = '\0';
ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
} else {
ZVAL_EMPTY_STRING(*ivec);
}
#endif
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_cleanup(&ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == -1) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
Commit Message:
CWE ID: CWE-754
Target: 1
Example 2:
Code: dissect_dch_tnl_congestion_indication(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset)
{
guint64 status;
/* Congestion status */
proto_tree_add_bits_ret_val(tree, hf_fp_congestion_status, tvb,
offset*8 + 6, 2, &status, ENC_BIG_ENDIAN);
offset++;
col_append_fstr(pinfo->cinfo, COL_INFO, " status = %s",
val_to_str_const((guint16)status, congestion_status_vals, "unknown"));
return offset;
}
Commit Message: UMTS_FP: fix handling reserved C/T value
The spec puts the reserved value at 0xf but our internal table has 'unknown' at
0; since all the other values seem to be offset-by-one, just take the modulus
0xf to avoid running off the end of the table.
Bug: 12191
Change-Id: I83c8fb66797bbdee52a2246fb1eea6e37cbc7eb0
Reviewed-on: https://code.wireshark.org/review/15722
Reviewed-by: Evan Huus <[email protected]>
Petri-Dish: Evan Huus <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[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 int ax25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied;
int err = 0;
lock_sock(sk);
/*
* This works for seqpacket too. The receiver has ordered the
* queue for us! We do one quick check first though
*/
if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
/* Now we can treat all alike */
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
if (!ax25_sk(sk)->pidincl)
skb_pull(skb, 1); /* Remove PID */
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (msg->msg_namelen != 0) {
struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;
ax25_digi digi;
ax25_address src;
const unsigned char *mac = skb_mac_header(skb);
memset(sax, 0, sizeof(struct full_sockaddr_ax25));
ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL,
&digi, NULL, NULL);
sax->sax25_family = AF_AX25;
/* We set this correctly, even though we may not let the
application know the digi calls further down (because it
did NOT ask to know them). This could get political... **/
sax->sax25_ndigis = digi.ndigi;
sax->sax25_call = src;
if (sax->sax25_ndigis != 0) {
int ct;
struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax;
for (ct = 0; ct < digi.ndigi; ct++)
fsa->fsa_digipeater[ct] = digi.calls[ct];
}
msg->msg_namelen = sizeof(struct full_sockaddr_ax25);
}
skb_free_datagram(sk, skb);
err = copied;
out:
release_sock(sk);
return err;
}
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
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 uio_mmap_physical(struct vm_area_struct *vma)
{
struct uio_device *idev = vma->vm_private_data;
int mi = uio_find_mem_index(vma);
if (mi < 0)
return -EINVAL;
vma->vm_ops = &uio_physical_vm_ops;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return remap_pfn_range(vma,
vma->vm_start,
idev->info->mem[mi].addr >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls
Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that
really should use the vm_iomap_memory() helper. This trivially converts
two of them to the helper, and comments about why the third one really
needs to continue to use remap_pfn_range(), and adds the missing size
check.
Reported-by: Nico Golde <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected].
CWE ID: CWE-119
Target: 1
Example 2:
Code: int local_opendir_nofollow(FsContext *fs_ctx, const char *path)
{
return local_open_nofollow(fs_ctx, path, O_DIRECTORY | O_RDONLY, 0);
}
Commit Message:
CWE ID: CWE-732
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
if (mNativeWindow != NULL && portIndex == kPortIndexOutput) {
return allocateOutputBuffersFromNativeWindow();
}
if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) {
ALOGE("protected output buffers must be stent to an ANativeWindow");
return PERMISSION_DENIED;
}
status_t err = OK;
if ((mFlags & kStoreMetaDataInVideoBuffers)
&& portIndex == kPortIndexInput) {
err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
if (err != OK) {
ALOGE("Storing meta data in video buffers is not supported");
return err;
}
}
OMX_PARAM_PORTDEFINITIONTYPE def;
InitOMXParams(&def);
def.nPortIndex = portIndex;
err = mOMX->getParameter(
mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
if (err != OK) {
return err;
}
CODEC_LOGV("allocating %u buffers of size %u on %s port",
def.nBufferCountActual, def.nBufferSize,
portIndex == kPortIndexInput ? "input" : "output");
if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) {
return BAD_VALUE;
}
size_t totalSize = def.nBufferCountActual * def.nBufferSize;
mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
CHECK(mem.get() != NULL);
BufferInfo info;
info.mData = NULL;
info.mSize = def.nBufferSize;
IOMX::buffer_id buffer;
if (portIndex == kPortIndexInput
&& ((mQuirks & kRequiresAllocateBufferOnInputPorts)
|| (mFlags & kUseSecureInputBuffers))) {
if (mOMXLivesLocally) {
mem.clear();
err = mOMX->allocateBuffer(
mNode, portIndex, def.nBufferSize, &buffer,
&info.mData);
} else {
err = mOMX->allocateBufferWithBackup(
mNode, portIndex, mem, &buffer, mem->size());
}
} else if (portIndex == kPortIndexOutput
&& (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
if (mOMXLivesLocally) {
mem.clear();
err = mOMX->allocateBuffer(
mNode, portIndex, def.nBufferSize, &buffer,
&info.mData);
} else {
err = mOMX->allocateBufferWithBackup(
mNode, portIndex, mem, &buffer, mem->size());
}
} else {
err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size());
}
if (err != OK) {
ALOGE("allocate_buffer_with_backup failed");
return err;
}
if (mem != NULL) {
info.mData = mem->pointer();
}
info.mBuffer = buffer;
info.mStatus = OWNED_BY_US;
info.mMem = mem;
info.mMediaBuffer = NULL;
if (portIndex == kPortIndexOutput) {
LOG_ALWAYS_FATAL_IF((mOMXLivesLocally
&& (mQuirks & kRequiresAllocateBufferOnOutputPorts)
&& (mQuirks & kDefersOutputBufferAllocation)),
"allocateBuffersOnPort cannot defer buffer allocation");
info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
info.mMediaBuffer->setObserver(this);
}
mPortBuffers[portIndex].push(info);
CODEC_LOGV("allocated buffer %u on %s port", buffer,
portIndex == kPortIndexInput ? "input" : "output");
}
if (portIndex == kPortIndexOutput) {
sp<MetaData> meta = mSource->getFormat();
int32_t delay = 0;
if (!meta->findInt32(kKeyEncoderDelay, &delay)) {
delay = 0;
}
int32_t padding = 0;
if (!meta->findInt32(kKeyEncoderPadding, &padding)) {
padding = 0;
}
int32_t numchannels = 0;
if (delay + padding) {
if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) {
size_t frameSize = numchannels * sizeof(int16_t);
if (mSkipCutBuffer != NULL) {
size_t prevbuffersize = mSkipCutBuffer->size();
if (prevbuffersize != 0) {
ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize);
}
}
mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize);
}
}
}
if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) {
Vector<MediaBuffer *> buffers;
for (size_t i = 0; i < def.nBufferCountActual; ++i) {
const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i);
MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize);
buffers.push(mbuf);
}
status_t err = mSource->setBuffers(buffers);
if (err != OK) {
for (size_t i = 0; i < def.nBufferCountActual; ++i) {
buffers.editItemAt(i)->release();
}
buffers.clear();
CODEC_LOGE(
"Codec requested to use secure input buffers but "
"upstream source didn't support that.");
return err;
}
}
return OK;
}
Commit Message: OMXCodec: check IMemory::pointer() before using allocation
Bug: 29421811
Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1
CWE ID: CWE-284
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 on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: int test_small_prime(BIO *bp,BN_CTX *ctx)
{
static const int bits = 10;
int ret = 0;
BIGNUM r;
BN_init(&r);
if (!BN_generate_prime_ex(&r, bits, 0, NULL, NULL, NULL))
goto err;
if (BN_num_bits(&r) != bits)
{
BIO_printf(bp, "Expected %d bit prime, got %d bit number\n", bits, BN_num_bits(&r));
goto err;
}
ret = 1;
err:
BN_clear(&r);
return ret;
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <[email protected]>
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig,
siginfo_t __user *, uinfo)
{
siginfo_t info;
if (copy_from_user(&info, uinfo, sizeof(siginfo_t)))
return -EFAULT;
return do_rt_sigqueueinfo(pid, sig, &info);
}
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
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: tiffcp(TIFF* in, TIFF* out)
{
uint16 bitspersample, samplesperpixel = 1;
uint16 input_compression, input_photometric = PHOTOMETRIC_MINISBLACK;
copyFunc cf;
uint32 width, length;
struct cpTag* p;
CopyField(TIFFTAG_IMAGEWIDTH, width);
CopyField(TIFFTAG_IMAGELENGTH, length);
CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
CopyField(TIFFTAG_COMPRESSION, compression);
TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression);
TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric);
if (input_compression == COMPRESSION_JPEG) {
/* Force conversion to RGB */
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else if (input_photometric == PHOTOMETRIC_YCBCR) {
/* Otherwise, can't handle subsampled input */
uint16 subsamplinghor,subsamplingver;
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsamplinghor, &subsamplingver);
if (subsamplinghor!=1 || subsamplingver!=1) {
fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n",
TIFFFileName(in));
return FALSE;
}
}
if (compression == COMPRESSION_JPEG) {
if (input_photometric == PHOTOMETRIC_RGB &&
jpegcolormode == JPEGCOLORMODE_RGB)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else if (compression == COMPRESSION_SGILOG
|| compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
samplesperpixel == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else if (input_compression == COMPRESSION_JPEG &&
samplesperpixel == 3 ) {
/* RGB conversion was forced above
hence the output will be of the same type */
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
}
else
CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT);
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/*
* Will copy `Orientation' tag from input image
*/
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
switch (orientation) {
case ORIENTATION_BOTRIGHT:
case ORIENTATION_RIGHTBOT: /* XXX */
TIFFWarning(TIFFFileName(in), "using bottom-left orientation");
orientation = ORIENTATION_BOTLEFT;
/* fall thru... */
case ORIENTATION_LEFTBOT: /* XXX */
case ORIENTATION_BOTLEFT:
break;
case ORIENTATION_TOPRIGHT:
case ORIENTATION_RIGHTTOP: /* XXX */
default:
TIFFWarning(TIFFFileName(in), "using top-left orientation");
orientation = ORIENTATION_TOPLEFT;
/* fall thru... */
case ORIENTATION_LEFTTOP: /* XXX */
case ORIENTATION_TOPLEFT:
break;
}
TIFFSetField(out, TIFFTAG_ORIENTATION, orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) -1)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) -1)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0) {
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP,
&rowsperstrip)) {
rowsperstrip =
TIFFDefaultStripSize(out, rowsperstrip);
}
if (rowsperstrip > length && rowsperstrip != (uint32)-1)
rowsperstrip = length;
}
else if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (samplesperpixel <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
break;
case COMPRESSION_JBIG:
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII);
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
case COMPRESSION_LZMA:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
if (preset != -1) {
if (compression == COMPRESSION_ADOBE_DEFLATE
|| compression == COMPRESSION_DEFLATE)
TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset);
else if (compression == COMPRESSION_LZMA)
TIFFSetField(out, TIFFTAG_LZMAPRESET, preset);
}
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS,
g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{
uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{
uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
cp++;
inknameslen += (strlen(cp) + 1);
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (pageInSeq == 1) {
if (pageNum < 0) /* only one input file */ {
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
} else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
} else {
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
cf = pickCopyFunc(in, out, bitspersample, samplesperpixel);
return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE);
}
Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and
cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and
http://bugzilla.maptools.org/show_bug.cgi?id=2657
CWE ID: CWE-119
Target: 1
Example 2:
Code: SCTP_STATIC int sctp_getsockopt_connectx3(struct sock* sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_getaddrs_old param;
sctp_assoc_t assoc_id = 0;
int err = 0;
if (len < sizeof(param))
return -EINVAL;
if (copy_from_user(¶m, optval, sizeof(param)))
return -EFAULT;
err = __sctp_setsockopt_connectx(sk,
(struct sockaddr __user *)param.addrs,
param.addr_num, &assoc_id);
if (err == 0 || err == -EINPROGRESS) {
if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
return -EFAULT;
if (put_user(sizeof(assoc_id), optlen))
return -EFAULT;
}
return err;
}
Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual status_t openSession(Vector<uint8_t> &sessionId) {
Parcel data, reply;
data.writeInterfaceToken(IDrm::getInterfaceDescriptor());
status_t status = remote()->transact(OPEN_SESSION, data, &reply);
if (status != OK) {
return status;
}
readVector(reply, sessionId);
return reply.readInt32();
}
Commit Message: Fix info leak vulnerability of IDrm
bug: 26323455
Change-Id: I25bb30d3666ab38d5150496375ed2f55ecb23ba8
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Frame* ReuseExistingWindow(LocalFrame& active_frame,
LocalFrame& lookup_frame,
const AtomicString& frame_name,
NavigationPolicy policy,
const KURL& destination_url) {
if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") &&
policy == kNavigationPolicyIgnore) {
if (Frame* frame = lookup_frame.FindFrameForNavigation(
frame_name, active_frame, destination_url)) {
if (!EqualIgnoringASCIICase(frame_name, "_self")) {
if (Page* page = frame->GetPage()) {
if (page == active_frame.GetPage())
page->GetFocusController().SetFocusedFrame(frame);
else
page->GetChromeClient().Focus();
}
}
return frame;
}
}
return nullptr;
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Target: 1
Example 2:
Code: blk_status_t errno_to_blk_status(int errno)
{
int i;
for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
if (blk_errors[i].errno == errno)
return (__force blk_status_t)i;
}
return BLK_STS_IOERR;
}
Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case
We find the memory use-after-free issue in __blk_drain_queue()
on the kernel 4.14. After read the latest kernel 4.18-rc6 we
think it has the same problem.
Memory is allocated for q->fq in the blk_init_allocated_queue().
If the elevator init function called with error return, it will
run into the fail case to free the q->fq.
Then the __blk_drain_queue() uses the same memory after the free
of the q->fq, it will lead to the unpredictable event.
The patch is to set q->fq as NULL in the fail case of
blk_init_allocated_queue().
Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery")
Cc: <[email protected]>
Reviewed-by: Ming Lei <[email protected]>
Reviewed-by: Bart Van Assche <[email protected]>
Signed-off-by: xiao jin <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
{
if (h.isFixed())
return computeContentBoxLogicalHeight(h.value());
if (isRenderView())
return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
if (isTableCell() && (h.isAuto() || h.isPercent()))
return overrideHeight() - borderAndPaddingLogicalWidth();
if (h.isPercent())
return computeContentBoxLogicalHeight(h.calcValue(containingBlock()->availableLogicalHeight()));
if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
LayoutUnit oldHeight = block->logicalHeight();
block->computeLogicalHeight();
LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
block->setLogicalHeight(oldHeight);
return computeContentBoxLogicalHeight(newHeight);
}
return containingBlock()->availableLogicalHeight();
}
Commit Message: Source/WebCore: Fix for bug 64046 - Wrong image height in absolutely positioned div in
relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
Test: fast/css/absolute-child-with-percent-height-inside-relative-parent.html
* rendering/RenderBox.cpp:
(WebCore::RenderBox::availableLogicalHeightUsing):
LayoutTests: Test to cover absolutely positioned child with percentage height
in relatively positioned parent with bottom padding.
https://bugs.webkit.org/show_bug.cgi?id=64046
Patch by Kulanthaivel Palanichamy <[email protected]> on 2011-07-21
Reviewed by David Hyatt.
* fast/css/absolute-child-with-percent-height-inside-relative-parent-expected.txt: Added.
* fast/css/absolute-child-with-percent-height-inside-relative-parent.html: Added.
git-svn-id: svn://svn.chromium.org/blink/trunk@91533 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.