prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *sockaddr_url, *stratum_port, *tmp;
char *url, *port, address[256];
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
else {
char *dot_pool, *dot_reconnect;
dot_pool = strchr(pool->sockaddr_url, '.');
if (!dot_pool) {
applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
pool->sockaddr_url);
return false;
}
dot_reconnect = strchr(url, '.');
if (!dot_reconnect) {
applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
url);
return false;
}
if (strcmp(dot_pool, dot_reconnect)) {
applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
pool->sockaddr_url);
return false;
}
}
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
sprintf(address, "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct se_node_acl *tcm_loop_tpg_alloc_fabric_acl(
struct se_portal_group *se_tpg)
{
struct tcm_loop_nacl *tl_nacl;
tl_nacl = kzalloc(sizeof(struct tcm_loop_nacl), GFP_KERNEL);
if (!tl_nacl) {
printk(KERN_ERR "Unable to allocate struct tcm_loop_nacl\n");
return NULL;
}
return &tl_nacl->se_node_acl;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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::CancelPendingJavaScriptUrl() {
if (javascript_url_task_handle_.IsActive())
javascript_url_task_handle_.Cancel();
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (tmpName[i] != 0) && (i < to_read) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void MaybeEncodeTextContent(const String& text_content,
const char* buffer_data,
size_t buffer_size,
String* result,
bool* base64_encoded) {
if (!text_content.IsNull() &&
!text_content.Utf8(WTF::kStrictUTF8Conversion).IsNull()) {
*result = text_content;
*base64_encoded = false;
} else if (buffer_data) {
*result = Base64Encode(buffer_data, buffer_size);
*base64_encoded = true;
} else if (text_content.IsNull()) {
*result = "";
*base64_encoded = false;
} else {
DCHECK(!text_content.Is8Bit());
*result = Base64Encode(text_content.Utf8(WTF::kLenientUTF8Conversion));
*base64_encoded = true;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
ND_TCHECK2(p[0], 3);
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_atm2]"));
return l2info.header_len;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: on_register_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gchar *cfg_desc,
gpointer user_data)
{
struct tcmur_handler *handler;
struct dbus_info *info;
char *bus_name;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
subtype);
handler = g_new0(struct tcmur_handler, 1);
handler->subtype = g_strdup(subtype);
handler->cfg_desc = g_strdup(cfg_desc);
handler->open = dbus_handler_open;
handler->close = dbus_handler_close;
handler->handle_cmd = dbus_handler_handle_cmd;
info = g_new0(struct dbus_info, 1);
info->register_invocation = invocation;
info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
bus_name,
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_handler_appeared,
on_handler_vanished,
handler,
NULL);
g_free(bus_name);
handler->opaque = info;
return TRUE;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void fcrypt_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
const struct fcrypt_ctx *ctx = crypto_tfm_ctx(tfm);
struct {
__be32 l, r;
} X;
memcpy(&X, src, sizeof(X));
F_ENCRYPT(X.l, X.r, ctx->sched[0xf]);
F_ENCRYPT(X.r, X.l, ctx->sched[0xe]);
F_ENCRYPT(X.l, X.r, ctx->sched[0xd]);
F_ENCRYPT(X.r, X.l, ctx->sched[0xc]);
F_ENCRYPT(X.l, X.r, ctx->sched[0xb]);
F_ENCRYPT(X.r, X.l, ctx->sched[0xa]);
F_ENCRYPT(X.l, X.r, ctx->sched[0x9]);
F_ENCRYPT(X.r, X.l, ctx->sched[0x8]);
F_ENCRYPT(X.l, X.r, ctx->sched[0x7]);
F_ENCRYPT(X.r, X.l, ctx->sched[0x6]);
F_ENCRYPT(X.l, X.r, ctx->sched[0x5]);
F_ENCRYPT(X.r, X.l, ctx->sched[0x4]);
F_ENCRYPT(X.l, X.r, ctx->sched[0x3]);
F_ENCRYPT(X.r, X.l, ctx->sched[0x2]);
F_ENCRYPT(X.l, X.r, ctx->sched[0x1]);
F_ENCRYPT(X.r, X.l, ctx->sched[0x0]);
memcpy(dst, &X, sizeof(X));
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 DeserializeNotificationDatabaseData(const std::string& input,
NotificationDatabaseData* output) {
DCHECK(output);
NotificationDatabaseDataProto message;
if (!message.ParseFromString(input))
return false;
output->notification_id = message.notification_id();
output->origin = GURL(message.origin());
output->service_worker_registration_id =
message.service_worker_registration_id();
PlatformNotificationData* notification_data = &output->notification_data;
const NotificationDatabaseDataProto::NotificationData& payload =
message.notification_data();
notification_data->title = base::UTF8ToUTF16(payload.title());
switch (payload.direction()) {
case NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT:
notification_data->direction =
PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT;
break;
case NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT:
notification_data->direction =
PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT;
break;
case NotificationDatabaseDataProto::NotificationData::AUTO:
notification_data->direction = PlatformNotificationData::DIRECTION_AUTO;
break;
}
notification_data->lang = payload.lang();
notification_data->body = base::UTF8ToUTF16(payload.body());
notification_data->tag = payload.tag();
notification_data->icon = GURL(payload.icon());
if (payload.vibration_pattern().size() > 0) {
notification_data->vibration_pattern.assign(
payload.vibration_pattern().begin(), payload.vibration_pattern().end());
}
notification_data->timestamp =
base::Time::FromInternalValue(payload.timestamp());
notification_data->silent = payload.silent();
notification_data->require_interaction = payload.require_interaction();
if (payload.data().length()) {
notification_data->data.assign(payload.data().begin(),
payload.data().end());
}
for (const auto& payload_action : payload.actions()) {
PlatformNotificationAction action;
action.action = payload_action.action();
action.title = base::UTF8ToUTF16(payload_action.title());
notification_data->actions.push_back(action);
}
return true;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE SoftRaw::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.raw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mChannelCount = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void testCrash_Report2418192() {
helperTestQueryString("http://svcs.cnn.com/weather/wrapper.jsp?&csiID=csi1", 1);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: vc4_get_hang_state_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_get_hang_state *get_state = data;
struct drm_vc4_get_hang_state_bo *bo_state;
struct vc4_hang_state *kernel_state;
struct drm_vc4_get_hang_state *state;
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned long irqflags;
u32 i;
int ret = 0;
spin_lock_irqsave(&vc4->job_lock, irqflags);
kernel_state = vc4->hang_state;
if (!kernel_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return -ENOENT;
}
state = &kernel_state->user_state;
/* If the user's array isn't big enough, just return the
* required array size.
*/
if (get_state->bo_count < state->bo_count) {
get_state->bo_count = state->bo_count;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return 0;
}
vc4->hang_state = NULL;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* Save the user's BO pointer, so we don't stomp it with the memcpy. */
state->bo = get_state->bo;
memcpy(get_state, state, sizeof(*state));
bo_state = kcalloc(state->bo_count, sizeof(*bo_state), GFP_KERNEL);
if (!bo_state) {
ret = -ENOMEM;
goto err_free;
}
for (i = 0; i < state->bo_count; i++) {
struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]);
u32 handle;
ret = drm_gem_handle_create(file_priv, kernel_state->bo[i],
&handle);
if (ret) {
state->bo_count = i - 1;
goto err;
}
bo_state[i].handle = handle;
bo_state[i].paddr = vc4_bo->base.paddr;
bo_state[i].size = vc4_bo->base.base.size;
}
if (copy_to_user((void __user *)(uintptr_t)get_state->bo,
bo_state,
state->bo_count * sizeof(*bo_state)))
ret = -EFAULT;
kfree(bo_state);
err_free:
vc4_free_hang_state(dev, kernel_state);
err:
return ret;
}
CWE ID: CWE-388
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
return network_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: virtual void drawLayersOnCCThread(CCLayerTreeHostImpl* impl)
{
if (!impl->sourceFrameNumber())
postSetNeedsCommitThenRedrawToMainThread();
else if (impl->sourceFrameNumber() == 1)
endTest();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 ResourceFetcher::DidLoadResourceFromMemoryCache(
unsigned long identifier,
Resource* resource,
const ResourceRequest& original_resource_request) {
ResourceRequest resource_request(resource->Url());
resource_request.SetFrameType(original_resource_request.GetFrameType());
resource_request.SetRequestContext(
original_resource_request.GetRequestContext());
Context().DispatchDidLoadResourceFromMemoryCache(identifier, resource_request,
resource->GetResponse());
Context().DispatchWillSendRequest(identifier, resource_request,
ResourceResponse() /* redirects */,
resource->Options().initiator_info);
Context().DispatchDidReceiveResponse(
identifier, resource->GetResponse(), resource_request.GetFrameType(),
resource_request.GetRequestContext(), resource,
FetchContext::ResourceResponseType::kFromMemoryCache);
if (resource->EncodedSize() > 0)
Context().DispatchDidReceiveData(identifier, 0, resource->EncodedSize());
Context().DispatchDidFinishLoading(
identifier, 0, 0, resource->GetResponse().DecodedBodyLength());
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool DragController::ConcludeEditDrag(DragData* drag_data) {
DCHECK(drag_data);
HTMLInputElement* file_input = file_input_element_under_mouse_;
if (file_input_element_under_mouse_) {
file_input_element_under_mouse_->SetCanReceiveDroppedFiles(false);
file_input_element_under_mouse_ = nullptr;
}
if (!document_under_mouse_)
return false;
LayoutPoint point = document_under_mouse_->View()->RootFrameToContents(
LayoutPoint(drag_data->ClientPosition()));
Element* element = ElementUnderMouse(document_under_mouse_.Get(), point);
if (!element)
return false;
LocalFrame* inner_frame = element->ownerDocument()->GetFrame();
DCHECK(inner_frame);
if (page_->GetDragCaret().HasCaret() &&
DispatchTextInputEventFor(inner_frame, drag_data) !=
DispatchEventResult::kNotCanceled)
return true;
if (drag_data->ContainsFiles() && file_input) {
if (file_input->GetLayoutObject())
DCHECK_EQ(file_input, element);
if (file_input->IsDisabledFormControl())
return false;
return file_input->ReceiveDroppedFiles(drag_data);
}
if (!page_->GetDragController().CanProcessDrag(
drag_data, inner_frame->LocalFrameRoot())) {
page_->GetDragCaret().Clear();
return false;
}
if (page_->GetDragCaret().HasCaret()) {
page_->GetDragCaret()
.CaretPosition()
.GetPosition()
.GetDocument()
->UpdateStyleAndLayoutIgnorePendingStylesheets();
}
const PositionWithAffinity& caret_position =
page_->GetDragCaret().CaretPosition();
if (!caret_position.IsConnected()) {
page_->GetDragCaret().Clear();
return false;
}
VisibleSelection drag_caret = CreateVisibleSelection(
SelectionInDOMTree::Builder().Collapse(caret_position).Build());
page_->GetDragCaret().Clear();
if (!inner_frame->Selection().IsAvailable()) {
return false;
}
Range* range = CreateRange(drag_caret.ToNormalizedEphemeralRange());
Element* root_editable_element =
inner_frame->Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement();
if (!range)
return false;
ResourceFetcher* fetcher = range->OwnerDocument().Fetcher();
ResourceCacheValidationSuppressor validation_suppressor(fetcher);
inner_frame->GetEditor().RegisterCommandGroup(
DragAndDropCommand::Create(*inner_frame->GetDocument()));
if (DragIsMove(inner_frame->Selection(), drag_data) ||
IsRichlyEditablePosition(drag_caret.Base())) {
DragSourceType drag_source_type = DragSourceType::kHTMLSource;
DocumentFragment* fragment = DocumentFragmentFromDragData(
drag_data, inner_frame, range, true, drag_source_type);
if (!fragment)
return false;
if (DragIsMove(inner_frame->Selection(), drag_data)) {
const DeleteMode delete_mode =
inner_frame->GetEditor().SmartInsertDeleteEnabled()
? DeleteMode::kSmart
: DeleteMode::kSimple;
const InsertMode insert_mode =
(delete_mode == DeleteMode::kSmart &&
inner_frame->Selection().Granularity() == TextGranularity::kWord &&
drag_data->CanSmartReplace())
? InsertMode::kSmart
: InsertMode::kSimple;
if (!inner_frame->GetEditor().DeleteSelectionAfterDraggingWithEvents(
inner_frame->GetEditor().FindEventTargetFrom(
inner_frame->Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()),
delete_mode, drag_caret.Base()))
return false;
inner_frame->Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
.SetBaseAndExtent(EphemeralRange(range))
.Build());
if (inner_frame->Selection().IsAvailable()) {
DCHECK(document_under_mouse_);
if (!inner_frame->GetEditor().ReplaceSelectionAfterDraggingWithEvents(
element, drag_data, fragment, range, insert_mode,
drag_source_type))
return false;
}
} else {
if (SetSelectionToDragCaret(inner_frame, drag_caret, range, point)) {
DCHECK(document_under_mouse_);
if (!inner_frame->GetEditor().ReplaceSelectionAfterDraggingWithEvents(
element, drag_data, fragment, range,
drag_data->CanSmartReplace() ? InsertMode::kSmart
: InsertMode::kSimple,
drag_source_type))
return false;
}
}
} else {
String text = drag_data->AsPlainText();
if (text.IsEmpty())
return false;
if (SetSelectionToDragCaret(inner_frame, drag_caret, range, point)) {
DCHECK(document_under_mouse_);
if (!inner_frame->GetEditor().ReplaceSelectionAfterDraggingWithEvents(
element, drag_data,
CreateFragmentFromText(EphemeralRange(range), text), range,
InsertMode::kSimple, DragSourceType::kPlainTextSource))
return false;
}
}
if (root_editable_element) {
if (LocalFrame* frame = root_editable_element->GetDocument().GetFrame()) {
frame->GetEventHandler().UpdateDragStateAfterEditDragIfNeeded(
root_editable_element);
}
}
return true;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample_index)
{
png_uint_32 bit_index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
bit_index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
bit_index *= 3;
if (colour_type & 4)
bit_index += x; /* Alpha channel */
/* Multiple channels; select one: */
if (colour_type & (2+4))
bit_index += sample_index * bit_depth;
}
/* Return the sample from the row as an integer. */
row += bit_index >> 3;
result = *row;
if (bit_depth == 8)
return result;
else if (bit_depth > 8)
return (result << 8) + *++row;
/* Less than 8 bits per sample. */
bit_index &= 7;
return (result >> (8-bit_index-bit_depth)) & ((1U<<bit_depth)-1);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
unsigned int *width, unsigned int *height, int *flip_image)
{
int palette_size;
unsigned char tga[TGA_HEADER_SIZE];
unsigned char id_len, /*cmap_type,*/ image_type;
unsigned char pixel_depth, image_desc;
unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
unsigned short /*x_origin, y_origin,*/ image_w, image_h;
if (!bits_per_pixel || !width || !height || !flip_image) {
return 0;
}
if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0 ;
}
id_len = tga[0];
/*cmap_type = tga[1];*/
image_type = tga[2];
/*cmap_index = get_ushort(&tga[3]);*/
cmap_len = get_ushort(&tga[5]);
cmap_entry_size = tga[7];
#if 0
x_origin = get_ushort(&tga[8]);
y_origin = get_ushort(&tga[10]);
#endif
image_w = get_ushort(&tga[12]);
image_h = get_ushort(&tga[14]);
pixel_depth = tga[16];
image_desc = tga[17];
*bits_per_pixel = (unsigned int)pixel_depth;
*width = (unsigned int)image_w;
*height = (unsigned int)image_h;
/* Ignore tga identifier, if present ... */
if (id_len) {
unsigned char *id = (unsigned char *) malloc(id_len);
if (id == 0) {
fprintf(stderr, "tga_readheader: memory out\n");
return 0;
}
if (!fread(id, id_len, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
free(id);
return 0 ;
}
free(id);
}
/* Test for compressed formats ... not yet supported ...
if (image_type > 8) {
fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
return 0 ;
}
*flip_image = !(image_desc & 32);
/* Palettized formats are not yet supported, skip over the palette, if present ... */
palette_size = cmap_len * (cmap_entry_size / 8);
if (palette_size > 0) {
fprintf(stderr, "File contains a palette - not yet supported.");
fseek(fp, palette_size, SEEK_CUR);
}
return 1;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: int vnc_zywrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
{
vs->zrle.type = VNC_ENCODING_ZYWRLE;
return zrle_send_framebuffer_update(vs, x, y, w, h);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
{
WARN_ON(mmu_is_nested(vcpu));
if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
return 1;
kvm_mmu_unload(vcpu);
kvm_init_shadow_ept_mmu(vcpu,
to_vmx(vcpu)->nested.msrs.ept_caps &
VMX_EPT_EXECUTE_ONLY_BIT,
nested_ept_ad_enabled(vcpu));
vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
return 0;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
Reference ref) {
PersistentHistogramData* data =
memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
const size_t length = memory_allocator_->GetAllocSize(ref);
if (!data || data->name[0] == '\0' ||
reinterpret_cast<char*>(data)[length - 1] != '\0' ||
data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
(data->logged_metadata.id != data->samples_metadata.id &&
data->logged_metadata.id != data->samples_metadata.id + 1) ||
HashMetricName(data->name) != data->samples_metadata.id) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA);
NOTREACHED();
return nullptr;
}
return CreateHistogram(data);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static char *get_trace_buf(void)
{
struct trace_buffer_struct *buffer = this_cpu_ptr(trace_percpu_buffer);
if (!buffer || buffer->nesting >= 4)
return NULL;
buffer->nesting++;
/* Interrupts must see nesting incremented before we use the buffer */
barrier();
return &buffer->buffer[buffer->nesting][0];
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 * gdImageGifPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
gdImageGifCtx (im, out);
rv = gdDPExtractData (out, size);
out->gd_free (out);
return rv;
}
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool LookupMatchInTopDomains(base::StringPiece skeleton) {
DCHECK_NE(skeleton.back(), '.');
auto labels = base::SplitStringPiece(skeleton, ".", base::KEEP_WHITESPACE,
base::SPLIT_WANT_ALL);
if (labels.size() > kNumberOfLabelsToCheck) {
labels.erase(labels.begin(),
labels.begin() + labels.size() - kNumberOfLabelsToCheck);
}
while (labels.size() > 1) {
std::string partial_skeleton = base::JoinString(labels, ".");
if (net::LookupStringInFixedSet(
g_graph, g_graph_length, partial_skeleton.data(),
partial_skeleton.length()) != net::kDafsaNotFound)
return true;
labels.erase(labels.begin());
}
return false;
}
CWE ID:
Target: 1
Example 2:
Code: bool AppCacheUpdateJob::ShouldSkipUrlFetch(const AppCacheEntry& entry) {
if (entry.IsExplicit() || entry.IsFallback() || entry.IsIntercept())
return false;
return false;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 JSValueRef releaseTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
int index = static_cast<int>(JSValueToNumber(context, arguments[0], exception));
ASSERT(!exception || !*exception);
if (index < 0 || index >= (int)touches.size())
return JSValueMakeUndefined(context);
touches[index].m_state = BlackBerry::Platform::TouchPoint::TouchReleased;
return JSValueMakeUndefined(context);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
netdev->ethtool_ops = &atl2_ethtool_ops;
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX;
netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX);
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
setup_timer(&adapter->watchdog_timer, atl2_watchdog,
(unsigned long)adapter);
setup_timer(&adapter->phy_config_timer, atl2_phy_config,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void cipso_v4_doi_free_rcu(struct rcu_head *entry)
{
struct cipso_v4_doi *doi_def;
doi_def = container_of(entry, struct cipso_v4_doi, rcu);
cipso_v4_doi_free(doi_def);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,
unsigned long dst_start,
unsigned long src_start,
unsigned long len,
bool zeropage,
bool *mmap_changing)
{
struct vm_area_struct *dst_vma;
ssize_t err;
pmd_t *dst_pmd;
unsigned long src_addr, dst_addr;
long copied;
struct page *page;
/*
* Sanitize the command parameters:
*/
BUG_ON(dst_start & ~PAGE_MASK);
BUG_ON(len & ~PAGE_MASK);
/* Does the address range wrap, or is the span zero-sized? */
BUG_ON(src_start + len <= src_start);
BUG_ON(dst_start + len <= dst_start);
src_addr = src_start;
dst_addr = dst_start;
copied = 0;
page = NULL;
retry:
down_read(&dst_mm->mmap_sem);
/*
* If memory mappings are changing because of non-cooperative
* operation (e.g. mremap) running in parallel, bail out and
* request the user to retry later
*/
err = -EAGAIN;
if (mmap_changing && READ_ONCE(*mmap_changing))
goto out_unlock;
/*
* Make sure the vma is not shared, that the dst range is
* both valid and fully within a single existing vma.
*/
err = -ENOENT;
dst_vma = find_vma(dst_mm, dst_start);
if (!dst_vma)
goto out_unlock;
/*
* Be strict and only allow __mcopy_atomic on userfaultfd
* registered ranges to prevent userland errors going
* unnoticed. As far as the VM consistency is concerned, it
* would be perfectly safe to remove this check, but there's
* no useful usage for __mcopy_atomic ouside of userfaultfd
* registered ranges. This is after all why these are ioctls
* belonging to the userfaultfd and not syscalls.
*/
if (!dst_vma->vm_userfaultfd_ctx.ctx)
goto out_unlock;
if (dst_start < dst_vma->vm_start ||
dst_start + len > dst_vma->vm_end)
goto out_unlock;
err = -EINVAL;
/*
* shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
* it will overwrite vm_ops, so vma_is_anonymous must return false.
*/
if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
dst_vma->vm_flags & VM_SHARED))
goto out_unlock;
/*
* If this is a HUGETLB vma, pass off to appropriate routine
*/
if (is_vm_hugetlb_page(dst_vma))
return __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,
src_start, len, zeropage);
if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
goto out_unlock;
/*
* Ensure the dst_vma has a anon_vma or this page
* would get a NULL anon_vma when moved in the
* dst_vma.
*/
err = -ENOMEM;
if (!(dst_vma->vm_flags & VM_SHARED) &&
unlikely(anon_vma_prepare(dst_vma)))
goto out_unlock;
while (src_addr < src_start + len) {
pmd_t dst_pmdval;
BUG_ON(dst_addr >= dst_start + len);
dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
if (unlikely(!dst_pmd)) {
err = -ENOMEM;
break;
}
dst_pmdval = pmd_read_atomic(dst_pmd);
/*
* If the dst_pmd is mapped as THP don't
* override it and just be strict.
*/
if (unlikely(pmd_trans_huge(dst_pmdval))) {
err = -EEXIST;
break;
}
if (unlikely(pmd_none(dst_pmdval)) &&
unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {
err = -ENOMEM;
break;
}
/* If an huge pmd materialized from under us fail */
if (unlikely(pmd_trans_huge(*dst_pmd))) {
err = -EFAULT;
break;
}
BUG_ON(pmd_none(*dst_pmd));
BUG_ON(pmd_trans_huge(*dst_pmd));
err = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
src_addr, &page, zeropage);
cond_resched();
if (unlikely(err == -ENOENT)) {
void *page_kaddr;
up_read(&dst_mm->mmap_sem);
BUG_ON(!page);
page_kaddr = kmap(page);
err = copy_from_user(page_kaddr,
(const void __user *) src_addr,
PAGE_SIZE);
kunmap(page);
if (unlikely(err)) {
err = -EFAULT;
goto out;
}
goto retry;
} else
BUG_ON(page);
if (!err) {
dst_addr += PAGE_SIZE;
src_addr += PAGE_SIZE;
copied += PAGE_SIZE;
if (fatal_signal_pending(current))
err = -EINTR;
}
if (err)
break;
}
out_unlock:
up_read(&dst_mm->mmap_sem);
out:
if (page)
put_page(page);
BUG_ON(copied < 0);
BUG_ON(err > 0);
BUG_ON(!copied && !err);
return copied ? copied : err;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key)
{
unsigned long modulus_bitlen, modulus_bytelen, x;
int err;
unsigned char *tmpbuf;
LTC_ARGCHK(hash != NULL);
LTC_ARGCHK(sig != NULL);
LTC_ARGCHK(stat != NULL);
LTC_ARGCHK(key != NULL);
/* default to invalid */
*stat = 0;
/* valid padding? */
if ((padding != LTC_PKCS_1_V1_5) &&
(padding != LTC_PKCS_1_PSS)) {
return CRYPT_PK_INVALID_PADDING;
}
if (padding == LTC_PKCS_1_PSS) {
/* valid hash ? */
if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
return err;
}
}
/* get modulus len in bits */
modulus_bitlen = mp_count_bits( (key->N));
/* outlen must be at least the size of the modulus */
modulus_bytelen = mp_unsigned_bin_size( (key->N));
if (modulus_bytelen != siglen) {
return CRYPT_INVALID_PACKET;
}
/* allocate temp buffer for decoded sig */
tmpbuf = XMALLOC(siglen);
if (tmpbuf == NULL) {
return CRYPT_MEM;
}
/* RSA decode it */
x = siglen;
if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
XFREE(tmpbuf);
return err;
}
/* make sure the output is the right size */
if (x != siglen) {
XFREE(tmpbuf);
return CRYPT_INVALID_PACKET;
}
if (padding == LTC_PKCS_1_PSS) {
/* PSS decode and verify it */
if(modulus_bitlen%8 == 1){
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf+1, x-1, saltlen, hash_idx, modulus_bitlen, stat);
}
else{
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf, x, saltlen, hash_idx, modulus_bitlen, stat);
}
} else {
/* PKCS #1 v1.5 decode it */
unsigned char *out;
unsigned long outlen, loid[16];
int decoded;
ltc_asn1_list digestinfo[2], siginfo[2];
/* not all hashes have OIDs... so sad */
if (hash_descriptor[hash_idx].OIDlen == 0) {
err = CRYPT_INVALID_ARG;
goto bail_2;
}
/* allocate temp buffer for decoded hash */
outlen = ((modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0)) - 3;
out = XMALLOC(outlen);
if (out == NULL) {
err = CRYPT_MEM;
goto bail_2;
}
if ((err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_PKCS_1_EMSA, modulus_bitlen, out, &outlen, &decoded)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* now we must decode out[0...outlen-1] using ASN.1, test the OID and then test the hash */
/* construct the SEQUENCE
SEQUENCE {
SEQUENCE {hashoid OID
blah NULL
}
hash OCTET STRING
}
*/
LTC_SET_ASN1(digestinfo, 0, LTC_ASN1_OBJECT_IDENTIFIER, loid, sizeof(loid)/sizeof(loid[0]));
LTC_SET_ASN1(digestinfo, 1, LTC_ASN1_NULL, NULL, 0);
LTC_SET_ASN1(siginfo, 0, LTC_ASN1_SEQUENCE, digestinfo, 2);
LTC_SET_ASN1(siginfo, 1, LTC_ASN1_OCTET_STRING, tmpbuf, siglen);
if ((err = der_decode_sequence(out, outlen, siginfo, 2)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* test OID */
if ((digestinfo[0].size == hash_descriptor[hash_idx].OIDlen) &&
(XMEMCMP(digestinfo[0].data, hash_descriptor[hash_idx].OID, sizeof(unsigned long) * hash_descriptor[hash_idx].OIDlen) == 0) &&
(siginfo[1].size == hashlen) &&
(XMEMCMP(siginfo[1].data, hash, hashlen) == 0)) {
*stat = 1;
}
#ifdef LTC_CLEAN_STACK
zeromem(out, outlen);
#endif
XFREE(out);
}
bail_2:
#ifdef LTC_CLEAN_STACK
zeromem(tmpbuf, siglen);
#endif
XFREE(tmpbuf);
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct nl_mmap_hdr *netlink_mmap_hdr(struct sk_buff *skb)
{
return (struct nl_mmap_hdr *)(skb->head - NL_MMAP_HDRLEN);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 FrameLoader::DispatchDidClearDocumentOfWindowObject() {
DCHECK(frame_->GetDocument());
if (state_machine_.CreatingInitialEmptyDocument())
return;
if (!frame_->GetDocument()->CanExecuteScripts(kNotAboutToExecuteScript))
return;
Settings* settings = frame_->GetSettings();
if (settings && settings->GetForceMainWorldInitialization()) {
frame_->GetScriptController().WindowProxy(DOMWrapperWorld::MainWorld());
}
probe::didClearDocumentOfWindowObject(frame_);
if (dispatching_did_clear_window_object_in_main_world_)
return;
base::AutoReset<bool> in_did_clear_window_object(
&dispatching_did_clear_window_object_in_main_world_, true);
Client()->DispatchDidClearWindowObjectInMainWorld();
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Segment::Segment(
IMkvReader* pReader,
long long elem_start,
long long start,
long long size) :
m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0)
{
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int kvm_arch_init_vm(struct kvm *kvm)
{
BUG_ON(!kvm);
kvm->arch.is_sn2 = ia64_platform_is("sn2");
kvm->arch.metaphysical_rr0 = GUEST_PHYSICAL_RR0;
kvm->arch.metaphysical_rr4 = GUEST_PHYSICAL_RR4;
kvm->arch.vmm_init_rr = VMM_INIT_RR;
/*
*Fill P2M entries for MMIO/IO ranges
*/
kvm_build_io_pmt(kvm);
INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
return 0;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfColumnHeaders()
{
return JSStringCreateWithCharacters(0, 0);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool RenderFrameImpl::SwapIn() {
CHECK_NE(proxy_routing_id_, MSG_ROUTING_NONE);
CHECK(!in_frame_tree_);
RenderFrameProxy* proxy = RenderFrameProxy::FromRoutingID(proxy_routing_id_);
CHECK(proxy);
unique_name_helper_.set_propagated_name(proxy->unique_name());
if (!proxy->web_frame()->Swap(frame_))
return false;
proxy_routing_id_ = MSG_ROUTING_NONE;
in_frame_tree_ = true;
if (is_main_frame_) {
CHECK(!render_view_->main_render_frame_);
render_view_->main_render_frame_ = this;
if (render_view_->GetWidget()->is_frozen()) {
render_view_->GetWidget()->SetIsFrozen(false);
}
render_view_->UpdateWebViewWithDeviceScaleFactor();
}
return true;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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_io_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return (NULL);
return (png_ptr->io_ptr);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value)
{
enum TIFFReadDirEntryErr err;
if (direntry->tdir_count!=1)
return(TIFFReadDirEntryErrCount);
switch (direntry->tdir_type)
{
case TIFF_BYTE:
{
uint8 m;
TIFFReadDirEntryCheckedByte(tif,direntry,&m);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_SBYTE:
{
int8 m;
TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
err=TIFFReadDirEntryCheckRangeLong8Sbyte(m);
if (err!=TIFFReadDirEntryErrOk)
return(err);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_SHORT:
{
uint16 m;
TIFFReadDirEntryCheckedShort(tif,direntry,&m);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_SSHORT:
{
int16 m;
TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
err=TIFFReadDirEntryCheckRangeLong8Sshort(m);
if (err!=TIFFReadDirEntryErrOk)
return(err);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_LONG:
{
uint32 m;
TIFFReadDirEntryCheckedLong(tif,direntry,&m);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_SLONG:
{
int32 m;
TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
err=TIFFReadDirEntryCheckRangeLong8Slong(m);
if (err!=TIFFReadDirEntryErrOk)
return(err);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
case TIFF_LONG8:
err=TIFFReadDirEntryCheckedLong8(tif,direntry,value);
return(err);
case TIFF_SLONG8:
{
int64 m;
err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
if (err!=TIFFReadDirEntryErrOk)
return(err);
err=TIFFReadDirEntryCheckRangeLong8Slong8(m);
if (err!=TIFFReadDirEntryErrOk)
return(err);
*value=(uint64)m;
return(TIFFReadDirEntryErrOk);
}
default:
return(TIFFReadDirEntryErrType);
}
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: inline float ParentTextZoomFactor(LocalFrame* frame) {
Frame* parent = frame->Tree().Parent();
if (!parent || !parent->IsLocalFrame())
return 1;
return ToLocalFrame(parent)->TextZoomFactor();
}
CWE ID: CWE-285
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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 != 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 != 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 != 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:{
if (pCmdData == NULL ||
cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (sizeof(effect_param_t) + sizeof(int32_t))){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *)pCmdData;
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,
&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 != 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 */
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void feh_wm_set_bg_centered(Pixmap pmap, Imlib_Image im, int use_filelist,
int x, int y, int w, int h)
{
int offset_x, offset_y;
if (use_filelist)
feh_wm_load_next(&im);
if(opt.geom_flags & XValue)
if(opt.geom_flags & XNegative)
offset_x = (w - gib_imlib_image_get_width(im)) + opt.geom_x;
else
offset_x = opt.geom_x;
else
offset_x = (w - gib_imlib_image_get_width(im)) >> 1;
if(opt.geom_flags & YValue)
if(opt.geom_flags & YNegative)
offset_y = (h - gib_imlib_image_get_height(im)) + opt.geom_y;
else
offset_y = opt.geom_y;
else
offset_y = (h - gib_imlib_image_get_height(im)) >> 1;
gib_imlib_render_image_part_on_drawable_at_size(pmap, im,
((offset_x < 0) ? -offset_x : 0),
((offset_y < 0) ? -offset_y : 0),
w,
h,
x + ((offset_x > 0) ? offset_x : 0),
y + ((offset_y > 0) ? offset_y : 0),
w,
h,
1, 0, 0);
if (use_filelist)
gib_imlib_free_image_and_decache(im);
return;
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 jas_iccputuint(jas_stream_t *out, int n, ulonglong val)
{
int i;
int c;
for (i = n; i > 0; --i) {
c = (val >> (8 * (i - 1))) & 0xff;
if (jas_stream_putc(out, c) == EOF)
return -1;
}
return 0;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: InitAliasInfo(AliasInfo *info, enum merge_mode merge,
xkb_atom_t alias, xkb_atom_t real)
{
memset(info, 0, sizeof(*info));
info->merge = merge;
info->alias = alias;
info->real = real;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsImpl::GenerateMHTML(
const base::FilePath& file,
const base::Callback<void(int64)>& callback) {
MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void comps_objrtree_unite(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key = malloc(sizeof(char)
* (strlen(((COMPS_ObjRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key + strlen(parent_pair->key),
((COMPS_ObjRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_ObjRTreeData*)it->data)->key) +1));
memcpy(pair->key, ((COMPS_ObjRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_ObjRTreeData*)it->data)->data != NULL) {
comps_objrtree_set(rt1, pair->key,
(((COMPS_ObjRTreeData*)it->data)->data));
}
if (((COMPS_ObjRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: entry_guard_add_to_sample_impl(guard_selection_t *gs,
const uint8_t *rsa_id_digest,
const char *nickname,
const tor_addr_port_t *bridge_addrport)
{
const int GUARD_LIFETIME = get_guard_lifetime();
tor_assert(gs);
/* Make sure we can actually identify the guard. */
if (BUG(!rsa_id_digest && !bridge_addrport))
return NULL; // LCOV_EXCL_LINE
entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
/* persistent fields */
guard->is_persistent = (rsa_id_digest != NULL);
guard->selection_name = tor_strdup(gs->name);
if (rsa_id_digest)
memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
if (nickname)
strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
tor_free(guard->sampled_by_version);
guard->sampled_by_version = tor_strdup(VERSION);
guard->currently_listed = 1;
guard->confirmed_idx = -1;
/* non-persistent fields */
guard->is_reachable = GUARD_REACHABLE_MAYBE;
if (bridge_addrport)
guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
smartlist_add(gs->sampled_entry_guards, guard);
guard->in_selection = gs;
entry_guard_set_filtered_flags(get_options(), gs, guard);
entry_guards_changed_for_guard_selection(gs);
return guard;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GF_Err tpay_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TPAYBox *ptr = (GF_TPAYBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nbBytes);
return GF_OK;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta,
gfx::Vector2dF overscroll_velocity) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(),
overscroll_delta.y(), overscroll_velocity.x(),
overscroll_velocity.y());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void DocumentLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
const KURL& url,
Document* owner_document,
WebGlobalObjectReusePolicy global_object_reuse_policy,
const String& source) {
InstallNewDocument(url, owner_document, global_object_reuse_policy,
MimeType(), response_.TextEncodingName(),
InstallNewDocumentReason::kJavascriptURL,
kForceSynchronousParsing, NullURL());
if (!source.IsNull()) {
frame_->GetDocument()->SetCompatibilityMode(Document::kNoQuirksMode);
parser_->Append(source);
}
if (parser_)
parser_->Finish();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: RTCSessionDescriptionRequestFailedTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request)
: MethodTask<MockWebRTCPeerConnectionHandler>(object)
, m_request(request)
{
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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_fxrstor(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
if (rc != X86EMUL_CONTINUE)
return rc;
if (fx_state.mxcsr >> 16)
return emulate_gp(ctxt, 0);
ctxt->ops->get_fpu(ctxt);
if (ctxt->mode < X86EMUL_MODE_PROT64)
rc = fxrstor_fixup(ctxt, &fx_state);
if (rc == X86EMUL_CONTINUE)
rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
ctxt->ops->put_fpu(ctxt);
return rc;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: sockaddr_inet(short family, inet_address_t *addr)
{
SOCKADDR_INET sa_inet;
ZeroMemory(&sa_inet, sizeof(sa_inet));
sa_inet.si_family = family;
if (family == AF_INET)
{
sa_inet.Ipv4.sin_addr = addr->ipv4;
}
else if (family == AF_INET6)
{
sa_inet.Ipv6.sin6_addr = addr->ipv6;
}
return sa_inet;
}
CWE ID: CWE-415
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebLocalFrameImpl::SetCommittedFirstRealLoad() {
DCHECK(GetFrame());
GetFrame()->Loader().StateMachine()->AdvanceTo(
FrameLoaderStateMachine::kCommittedMultipleRealLoads);
GetFrame()->DidSendResourceTimingInfoToParent();
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
chromeos::SetImePropertyActivated(
input_method_status_connection_, key.c_str(), activated);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int ehci_reset_queue(EHCIQueue *q)
{
int packets;
trace_usb_ehci_queue_action(q, "reset");
packets = ehci_cancel_queue(q);
q->dev = NULL;
q->qtdaddr = 0;
q->last_pid = 0;
return packets;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
(void)T1_ToFixedArray( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) {
for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();
++it) {
if ((*it)->GetAccountId() == account_id) {
users_.erase(it);
break;
}
}
}
CWE ID:
Target: 1
Example 2:
Code: MetricsWebContentsObserver::~MetricsWebContentsObserver() {}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 V8TestObject::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(V8TestObject::GetWrapperTypeInfo(), v8_value);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: SchedulerObject* SchedulerObject::getInstance()
{
if (!m_instance) {
m_instance = new SchedulerObject();
}
return m_instance;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 CuePoint::Load(IMkvReader* pReader) {
if (m_timecode >= 0) // already loaded
return;
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); // CuePoint ID
if (id != 0x3B)
return;
pos_ += len; // consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; // consume Size field
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x33) // CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) // CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
m_track_positions = new TrackPosition[m_track_positions_count];
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x37) { // CueTrackPosition(s) ID
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
CWE ID:
Target: 1
Example 2:
Code: static void __end_block_io_op(struct pending_req *pending_req, int error)
{
/* An error fails the entire request. */
if ((pending_req->operation == BLKIF_OP_FLUSH_DISKCACHE) &&
(error == -EOPNOTSUPP)) {
pr_debug(DRV_PFX "flush diskcache op failed, not supported\n");
xen_blkbk_flush_diskcache(XBT_NIL, pending_req->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if ((pending_req->operation == BLKIF_OP_WRITE_BARRIER) &&
(error == -EOPNOTSUPP)) {
pr_debug(DRV_PFX "write barrier op failed, not supported\n");
xen_blkbk_barrier(XBT_NIL, pending_req->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if (error) {
pr_debug(DRV_PFX "Buffer not up-to-date at end of operation,"
" error=%d\n", error);
pending_req->status = BLKIF_RSP_ERROR;
}
/*
* If all of the bio's have completed it is time to unmap
* the grant references associated with 'request' and provide
* the proper response on the ring.
*/
if (atomic_dec_and_test(&pending_req->pendcnt)) {
xen_blkbk_unmap(pending_req->blkif,
pending_req->segments,
pending_req->nr_pages);
make_response(pending_req->blkif, pending_req->id,
pending_req->operation, pending_req->status);
xen_blkif_put(pending_req->blkif);
if (atomic_read(&pending_req->blkif->refcnt) <= 2) {
if (atomic_read(&pending_req->blkif->drain))
complete(&pending_req->blkif->drain_complete);
}
free_req(pending_req->blkif, pending_req);
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 get_client_hello(SSL *s)
{
int i, n;
unsigned long len;
unsigned char *p;
STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */
STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */
STACK_OF(SSL_CIPHER) *prio, *allow;
int z;
/*
* This is a bit of a hack to check for the correct packet type the first
* time round.
*/
if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) {
s->first_packet = 1;
s->state = SSL2_ST_GET_CLIENT_HELLO_B;
}
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_HELLO_B) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 9 - s->init_num);
if (i < (9 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
s->init_num = 9;
if (*(p++) != SSL2_MT_CLIENT_HELLO) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_PEER_ERROR);
return (-1);
}
n2s(p, i);
if (i < s->version)
s->version = i;
n2s(p, i);
s->s2->tmp.cipher_spec_length = i;
n2s(p, i);
s->s2->tmp.session_id_length = i;
if ((i < 0) || (i > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
return -1;
}
n2s(p, i);
s->s2->challenge_length = i;
if ((i < SSL2_MIN_CHALLENGE_LENGTH) ||
(i > SSL2_MAX_CHALLENGE_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_INVALID_CHALLENGE_LENGTH);
return (-1);
}
s->state = SSL2_ST_GET_CLIENT_HELLO_C;
}
/* SSL2_ST_GET_CLIENT_HELLO_C */
p = (unsigned char *)s->init_buf->data;
len =
9 + (unsigned long)s->s2->tmp.cipher_spec_length +
(unsigned long)s->s2->challenge_length +
(unsigned long)s->s2->tmp.session_id_length;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
if (s->msg_callback) {
/* CLIENT-HELLO */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 9;
/*
* get session-id before cipher stuff so we can get out session structure
* if it is cached
*/
/* session-id */
if ((s->s2->tmp.session_id_length != 0) &&
(s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_BAD_SSL_SESSION_ID_LENGTH);
return (-1);
}
if (s->s2->tmp.session_id_length == 0) {
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
} else {
i = ssl_get_prev_session(s, &(p[s->s2->tmp.cipher_spec_length]),
s->s2->tmp.session_id_length, NULL);
if (i == 1) { /* previous session */
s->hit = 1;
} else if (i == -1) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
} else {
if (s->cert == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
}
if (!s->hit) {
cs = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.cipher_spec_length,
&s->session->ciphers);
if (cs == NULL)
goto mem_err;
cl = SSL_get_ciphers(s);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = sk_SSL_CIPHER_dup(cl);
if (prio == NULL)
goto mem_err;
allow = cs;
} else {
prio = cs;
allow = cl;
}
for (z = 0; z < sk_SSL_CIPHER_num(prio); z++) {
if (sk_SSL_CIPHER_find(allow, sk_SSL_CIPHER_value(prio, z)) < 0) {
(void)sk_SSL_CIPHER_delete(prio, z);
z--;
}
}
/*
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = prio;
}
/*
* s->session->ciphers should now have a list of ciphers that are on
* both the client and server. This list is ordered by the order the
if (s->s2->challenge_length > sizeof s->s2->challenge) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(s->s2->challenge, p, (unsigned int)s->s2->challenge_length);
return (1);
mem_err:
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_MALLOC_FAILURE);
return (0);
}
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context,
AVFrame* frame) {
VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt);
if (format == VideoFrame::UNKNOWN)
return AVERROR(EINVAL);
DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 ||
format == VideoFrame::YV12J);
gfx::Size size(codec_context->width, codec_context->height);
int ret;
if ((ret = av_image_check_size(size.width(), size.height(), 0, NULL)) < 0)
return ret;
gfx::Size natural_size;
if (codec_context->sample_aspect_ratio.num > 0) {
natural_size = GetNaturalSize(size,
codec_context->sample_aspect_ratio.num,
codec_context->sample_aspect_ratio.den);
} else {
natural_size = config_.natural_size();
}
if (!VideoFrame::IsValidConfig(format, size, gfx::Rect(size), natural_size))
return AVERROR(EINVAL);
scoped_refptr<VideoFrame> video_frame =
frame_pool_.CreateFrame(format, size, gfx::Rect(size),
natural_size, kNoTimestamp());
for (int i = 0; i < 3; i++) {
frame->base[i] = video_frame->data(i);
frame->data[i] = video_frame->data(i);
frame->linesize[i] = video_frame->stride(i);
}
frame->opaque = NULL;
video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque));
frame->type = FF_BUFFER_TYPE_USER;
frame->width = codec_context->width;
frame->height = codec_context->height;
frame->format = codec_context->pix_fmt;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void TraceTopFrame(Isolate* isolate) {
StackFrameIterator it(isolate);
if (it.done()) {
PrintF("unknown location (no JavaScript frames present)");
return;
}
StackFrame* raw_frame = it.frame();
if (raw_frame->is_internal()) {
Code* apply_builtin =
isolate->builtins()->builtin(Builtins::kFunctionPrototypeApply);
if (raw_frame->unchecked_code() == apply_builtin) {
PrintF("apply from ");
it.Advance();
raw_frame = it.frame();
}
}
JavaScriptFrame::PrintTop(isolate, stdout, false, true);
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void AllocatePixelCachePixels(CacheInfo *cache_info)
{
cache_info->mapped=MagickFalse;
cache_info->pixels=(PixelPacket *) MagickAssumeAligned(
AcquireAlignedMemory(1,(size_t) cache_info->length));
if (cache_info->pixels == (PixelPacket *) NULL)
{
cache_info->mapped=MagickTrue;
cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t)
cache_info->length);
}
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Segment::LoadCluster(
long long& pos,
long& len)
{
for (;;)
{
const long result = DoLoadCluster(pos, len);
if (result <= 1)
return result;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void n_tty_set_room(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
/* Did this open up the receive buffer? We may need to flip */
if (unlikely(ldata->no_room) && receive_room(tty)) {
ldata->no_room = 0;
WARN_RATELIMIT(tty->port->itty == NULL,
"scheduling with invalid itty\n");
/* see if ldisc has been killed - if so, this means that
* even though the ldisc has been halted and ->buf.work
* cancelled, ->buf.work is about to be rescheduled
*/
WARN_RATELIMIT(test_bit(TTY_LDISC_HALTED, &tty->flags),
"scheduling buffer work for halted ldisc\n");
queue_work(system_unbound_wq, &tty->port->buf.work);
}
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool freelist_state_initialize(union freelist_init_state *state,
struct kmem_cache *cachep,
unsigned int count)
{
bool ret;
unsigned int rand;
/* Use best entropy available to define a random shift */
rand = get_random_int();
/* Use a random state if the pre-computed list is not available */
if (!cachep->random_seq) {
prandom_seed_state(&state->rnd_state, rand);
ret = false;
} else {
state->list = cachep->random_seq;
state->count = count;
state->pos = 0;
state->rand = rand;
ret = true;
}
return ret;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void MediaStreamManager::CancelAllRequests(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto request_it = requests_.begin();
while (request_it != requests_.end()) {
if (request_it->second->requesting_process_id != render_process_id ||
request_it->second->requesting_frame_id != render_frame_id) {
++request_it;
continue;
}
const std::string label = request_it->first;
++request_it;
CancelRequest(label);
}
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static uint16_t tsc2102_data_register_read(TSC210xState *s, int reg)
{
switch (reg) {
case 0x00: /* X */
s->dav &= 0xfbff;
return TSC_CUT_RESOLUTION(X_TRANSFORM(s), s->precision) +
(s->noise & 3);
case 0x01: /* Y */
s->noise ++;
s->dav &= 0xfdff;
return TSC_CUT_RESOLUTION(Y_TRANSFORM(s), s->precision) ^
(s->noise & 3);
case 0x02: /* Z1 */
s->dav &= 0xfeff;
return TSC_CUT_RESOLUTION(Z1_TRANSFORM(s), s->precision) -
(s->noise & 3);
case 0x03: /* Z2 */
s->dav &= 0xff7f;
return TSC_CUT_RESOLUTION(Z2_TRANSFORM(s), s->precision) |
(s->noise & 3);
case 0x04: /* KPData */
if ((s->model & 0xff00) == 0x2300) {
if (s->kb.intr && (s->kb.mode & 2)) {
s->kb.intr = 0;
qemu_irq_raise(s->kbint);
}
return s->kb.down;
}
return 0xffff;
case 0x05: /* BAT1 */
s->dav &= 0xffbf;
return TSC_CUT_RESOLUTION(BAT1_VAL, s->precision) +
(s->noise & 6);
case 0x06: /* BAT2 */
s->dav &= 0xffdf;
return TSC_CUT_RESOLUTION(BAT2_VAL, s->precision);
case 0x07: /* AUX1 */
s->dav &= 0xffef;
return TSC_CUT_RESOLUTION(AUX1_VAL, s->precision);
case 0x08: /* AUX2 */
s->dav &= 0xfff7;
return 0xffff;
case 0x09: /* TEMP1 */
s->dav &= 0xfffb;
return TSC_CUT_RESOLUTION(TEMP1_VAL, s->precision) -
(s->noise & 5);
case 0x0a: /* TEMP2 */
s->dav &= 0xfffd;
return TSC_CUT_RESOLUTION(TEMP2_VAL, s->precision) ^
(s->noise & 3);
case 0x0b: /* DAC */
s->dav &= 0xfffe;
return 0xffff;
default:
#ifdef TSC_VERBOSE
fprintf(stderr, "tsc2102_data_register_read: "
"no such register: 0x%02x\n", reg);
#endif
return 0xffff;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionCode& ec)
{
RefPtr<ContainerNode> containerNode(container);
#if ENABLE(MUTATION_OBSERVERS)
ChildListMutationScope mutation(containerNode.get());
#endif
if (!fragment->firstChild()) {
containerNode->removeChildren();
return;
}
if (hasOneTextChild(containerNode.get()) && hasOneTextChild(fragment.get())) {
toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data(), ec);
return;
}
if (hasOneChild(containerNode.get())) {
containerNode->replaceChild(fragment, containerNode->firstChild(), ec);
return;
}
containerNode->removeChildren();
containerNode->appendChild(fragment, ec);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
{
__u64 start = F2FS_BYTES_TO_BLK(range->start);
__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
unsigned int start_segno, end_segno;
struct cp_control cpc;
int err = 0;
if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
return -EINVAL;
cpc.trimmed = 0;
if (end <= MAIN_BLKADDR(sbi))
goto out;
if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
f2fs_msg(sbi->sb, KERN_WARNING,
"Found FS corruption, run fsck to fix.");
goto out;
}
/* start/end segment number in main_area */
start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
GET_SEGNO(sbi, end);
cpc.reason = CP_DISCARD;
cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
/* do checkpoint to issue discard commands safely */
for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
cpc.trim_start = start_segno;
if (sbi->discard_blks == 0)
break;
else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
cpc.trim_end = end_segno;
else
cpc.trim_end = min_t(unsigned int,
rounddown(start_segno +
BATCHED_TRIM_SEGMENTS(sbi),
sbi->segs_per_sec) - 1, end_segno);
mutex_lock(&sbi->gc_mutex);
err = write_checkpoint(sbi, &cpc);
mutex_unlock(&sbi->gc_mutex);
if (err)
break;
schedule();
}
/* It's time to issue all the filed discards */
mark_discard_range_all(sbi);
f2fs_wait_discard_bios(sbi);
out:
range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Document::initSecurityContext()
{
if (haveInitializedSecurityOrigin()) {
ASSERT(securityOrigin());
return;
}
if (!m_frame) {
m_cookieURL = KURL(ParsedURLString, emptyString());
setSecurityOrigin(SecurityOrigin::createUnique());
setContentSecurityPolicy(ContentSecurityPolicy::create(this));
return;
}
m_cookieURL = m_url;
enforceSandboxFlags(m_frame->loader()->effectiveSandboxFlags());
setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
setContentSecurityPolicy(ContentSecurityPolicy::create(this));
if (Settings* settings = this->settings()) {
if (!settings->webSecurityEnabled()) {
securityOrigin()->grantUniversalAccess();
} else if (securityOrigin()->isLocal()) {
if (settings->allowUniversalAccessFromFileURLs() || m_frame->loader()->client()->shouldForceUniversalAccessFromLocalURL(m_url)) {
securityOrigin()->grantUniversalAccess();
} else if (!settings->allowFileAccessFromFileURLs()) {
securityOrigin()->enforceFilePathSeparation();
}
}
securityOrigin()->setStorageBlockingPolicy(settings->storageBlockingPolicy());
}
Document* parentDocument = ownerElement() ? ownerElement()->document() : 0;
if (parentDocument && m_frame->loader()->shouldTreatURLAsSrcdocDocument(url())) {
m_isSrcdocDocument = true;
setBaseURLOverride(parentDocument->baseURL());
}
m_mayDisplaySeamlesslyWithParent = isEligibleForSeamless(parentDocument, this);
if (!shouldInheritSecurityOriginFromOwner(m_url))
return;
Frame* ownerFrame = m_frame->tree()->parent();
if (!ownerFrame)
ownerFrame = m_frame->loader()->opener();
if (!ownerFrame) {
didFailToInitializeSecurityOrigin();
return;
}
if (isSandboxed(SandboxOrigin)) {
if (ownerFrame->document()->securityOrigin()->canLoadLocalResources())
securityOrigin()->grantLoadLocalResources();
return;
}
m_cookieURL = ownerFrame->document()->cookieURL();
setSecurityOrigin(ownerFrame->document()->securityOrigin());
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gss_unwrap_aead (minor_status,
context_handle,
input_message_buffer,
input_assoc_buffer,
output_payload_buffer,
conf_state,
qop_state)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_message_buffer;
gss_buffer_t input_assoc_buffer;
gss_buffer_t output_payload_buffer;
int *conf_state;
gss_qop_t *qop_state;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_unwrap_aead_args(minor_status, context_handle,
input_message_buffer, input_assoc_buffer,
output_payload_buffer,
conf_state, qop_state);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech)
return (GSS_S_BAD_MECH);
return gssint_unwrap_aead(mech, minor_status, ctx,
input_message_buffer, input_assoc_buffer,
output_payload_buffer, conf_state, qop_state);
}
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string MediaStreamManager::MakeMediaAccessRequest(
int render_process_id,
int render_frame_id,
int page_request_id,
const StreamControls& controls,
const url::Origin& security_origin,
MediaAccessRequestCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_DEVICE_ACCESS, controls,
MediaDeviceSaltAndOrigin{std::string() /* salt */,
std::string() /* group_id_salt */,
security_origin});
const std::string& label = AddRequest(request);
request->media_access_request_cb = std::move(callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
return label;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: Ins_SHPIX( TT_ExecContext exc,
FT_Long* args )
{
FT_F26Dot6 dx, dy;
FT_UShort point;
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
FT_Int B1, B2;
#endif
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
FT_Bool in_twilight = FT_BOOL( exc->GS.gep0 == 0 ||
exc->GS.gep1 == 0 ||
exc->GS.gep2 == 0 );
#endif
if ( exc->top < exc->GS.loop + 1 )
{
if ( exc->pedantic_hinting )
exc->error = FT_THROW( Invalid_Reference );
goto Fail;
}
dx = TT_MulFix14( args[0], exc->GS.freeVector.x );
dy = TT_MulFix14( args[0], exc->GS.freeVector.y );
while ( exc->GS.loop > 0 )
{
exc->args--;
point = (FT_UShort)exc->stack[exc->args];
if ( BOUNDS( point, exc->zp2.n_points ) )
{
if ( exc->pedantic_hinting )
{
exc->error = FT_THROW( Invalid_Reference );
return;
}
}
else
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
if ( SUBPIXEL_HINTING_INFINALITY )
{
/* If not using ignore_x_mode rendering, allow ZP2 move. */
/* If inline deltas aren't allowed, skip ZP2 move. */
/* If using ignore_x_mode rendering, allow ZP2 point move if: */
/* - freedom vector is y and sph_compatibility_mode is off */
/* - the glyph is composite and the move is in the Y direction */
/* - the glyph is specifically set to allow SHPIX moves */
/* - the move is on a previously Y-touched point */
if ( exc->ignore_x_mode )
{
/* save point for later comparison */
if ( exc->GS.freeVector.y != 0 )
B1 = exc->zp2.cur[point].y;
else
B1 = exc->zp2.cur[point].x;
if ( !exc->face->sph_compatibility_mode &&
exc->GS.freeVector.y != 0 )
{
Move_Zp2_Point( exc, point, dx, dy, TRUE );
/* save new point */
if ( exc->GS.freeVector.y != 0 )
{
B2 = exc->zp2.cur[point].y;
/* reverse any disallowed moves */
if ( ( exc->sph_tweak_flags & SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES ) &&
( B1 & 63 ) != 0 &&
( B2 & 63 ) != 0 &&
B1 != B2 )
Move_Zp2_Point( exc,
point,
NEG_LONG( dx ),
NEG_LONG( dy ),
TRUE );
}
}
else if ( exc->face->sph_compatibility_mode )
{
if ( exc->sph_tweak_flags & SPH_TWEAK_ROUND_NONPIXEL_Y_MOVES )
{
dx = FT_PIX_ROUND( B1 + dx ) - B1;
dy = FT_PIX_ROUND( B1 + dy ) - B1;
}
/* skip post-iup deltas */
if ( exc->iup_called &&
( ( exc->sph_in_func_flags & SPH_FDEF_INLINE_DELTA_1 ) ||
( exc->sph_in_func_flags & SPH_FDEF_INLINE_DELTA_2 ) ) )
goto Skip;
if ( !( exc->sph_tweak_flags & SPH_TWEAK_ALWAYS_SKIP_DELTAP ) &&
( ( exc->is_composite && exc->GS.freeVector.y != 0 ) ||
( exc->zp2.tags[point] & FT_CURVE_TAG_TOUCH_Y ) ||
( exc->sph_tweak_flags & SPH_TWEAK_DO_SHPIX ) ) )
Move_Zp2_Point( exc, point, 0, dy, TRUE );
/* save new point */
if ( exc->GS.freeVector.y != 0 )
{
B2 = exc->zp2.cur[point].y;
/* reverse any disallowed moves */
if ( ( B1 & 63 ) == 0 &&
( B2 & 63 ) != 0 &&
B1 != B2 )
Move_Zp2_Point( exc, point, 0, NEG_LONG( dy ), TRUE );
}
}
else if ( exc->sph_in_func_flags & SPH_FDEF_TYPEMAN_DIAGENDCTRL )
Move_Zp2_Point( exc, point, dx, dy, TRUE );
}
else
Move_Zp2_Point( exc, point, dx, dy, TRUE );
}
else
#endif
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
if ( SUBPIXEL_HINTING_MINIMAL &&
exc->backward_compatibility )
{
/* Special case: allow SHPIX to move points in the twilight zone. */
/* Otherwise, treat SHPIX the same as DELTAP. Unbreaks various */
/* fonts such as older versions of Rokkitt and DTL Argo T Light */
/* that would glitch severely after calling ALIGNRP after a */
/* blocked SHPIX. */
if ( in_twilight ||
( !( exc->iupx_called && exc->iupy_called ) &&
( ( exc->is_composite && exc->GS.freeVector.y != 0 ) ||
( exc->zp2.tags[point] & FT_CURVE_TAG_TOUCH_Y ) ) ) )
Move_Zp2_Point( exc, point, 0, dy, TRUE );
}
else
#endif
Move_Zp2_Point( exc, point, dx, dy, TRUE );
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
Skip:
#endif
exc->GS.loop--;
}
Fail:
exc->GS.loop = 1;
exc->new_top = exc->args;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 uint32_t *nfs_read_post_op_attr(uint32_t *p, struct inode *inode)
{
/*
* union post_op_attr switch (bool attributes_follow) {
* case TRUE:
* fattr3 attributes;
* case FALSE:
* void;
* };
*/
if (ntoh32(net_read_uint32(p++))) {
nfs_fattr3_to_stat(p, inode);
p += 21;
}
return p;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode image_clamping_mode,
ImageDecodingMode decode_mode) {
auto paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return;
auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode);
if (paint_image.decoding_mode() != paint_image_decoding_mode) {
paint_image = PaintImageBuilder::WithCopy(std::move(paint_image))
.set_decoding_mode(paint_image_decoding_mode)
.TakePaintImage();
}
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect,
image_clamping_mode, paint_image);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static __inline__ void isdn_net_zero_frame_cnt(isdn_net_local *lp)
{
atomic_set(&lp->frame_cnt, 0);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GF_Box *bloc_New()
{
ISOM_DECL_BOX_ALLOC(GF_BaseLocationBox, GF_ISOM_BOX_TYPE_TRIK);
return (GF_Box *)tmp;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
{
if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
(unsigned int)sk->sk_rcvbuf)
return -ENOMEM;
skb_orphan(skb);
skb->sk = sk;
skb->destructor = sock_rmem_free;
atomic_add(skb->truesize, &sk->sk_rmem_alloc);
/* before exiting rcu section, make sure dst is refcounted */
skb_dst_force(skb);
skb_queue_tail(&sk->sk_error_queue, skb);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk);
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: PanelWindowResizerTextDirectionTest() : is_rtl_(GetParam()) {}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 Extension::ProducePEM(const std::string& input, std::string* output) {
CHECK(output);
if (input.length() == 0)
return false;
return base::Base64Encode(input, output);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void inotify_free_group_priv(struct fsnotify_group *group)
{
/* ideally the idr is empty and we won't hit the BUG in teh callback */
idr_for_each(&group->inotify_data.idr, idr_callback, group);
idr_remove_all(&group->inotify_data.idr);
idr_destroy(&group->inotify_data.idr);
free_uid(group->inotify_data.user);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void tty_vhangup(struct tty_struct *tty)
{
tty_debug_hangup(tty, "vhangup\n");
__tty_hangup(tty, 0);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: RenderFrameSubmissionObserver::RenderFrameSubmissionObserver(
WebContents* web_contents)
: RenderFrameSubmissionObserver(
RenderFrameMetadataProviderFromWebContents(web_contents)) {}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: extern "C" int EffectCreate(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle){
int ret;
int i;
int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *);
const effect_descriptor_t *desc;
ALOGV("\t\nEffectCreate start");
if (pHandle == NULL || uuid == NULL){
ALOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer");
return -EINVAL;
}
for (i = 0; i < length; i++) {
desc = gDescriptors[i];
if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t))
== 0) {
ALOGV("\tEffectCreate - UUID matched Reverb type %d, UUID = %x", i, desc->uuid.timeLow);
break;
}
}
if (i == length) {
return -ENOENT;
}
ReverbContext *pContext = new ReverbContext;
pContext->itfe = &gReverbInterface;
pContext->hInstance = NULL;
pContext->auxiliary = false;
if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY){
pContext->auxiliary = true;
ALOGV("\tEffectCreate - AUX");
}else{
ALOGV("\tEffectCreate - INS");
}
pContext->preset = false;
if (memcmp(&desc->type, SL_IID_PRESETREVERB, sizeof(effect_uuid_t)) == 0) {
pContext->preset = true;
pContext->curPreset = REVERB_PRESET_LAST + 1;
pContext->nextPreset = REVERB_DEFAULT_PRESET;
ALOGV("\tEffectCreate - PRESET");
}else{
ALOGV("\tEffectCreate - ENVIRONMENTAL");
}
ALOGV("\tEffectCreate - Calling Reverb_init");
ret = Reverb_init(pContext);
if (ret < 0){
ALOGV("\tLVM_ERROR : EffectCreate() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
#ifdef LVM_PCM
pContext->PcmInPtr = NULL;
pContext->PcmOutPtr = NULL;
pContext->PcmInPtr = fopen("/data/tmp/reverb_pcm_in.pcm", "w");
pContext->PcmOutPtr = fopen("/data/tmp/reverb_pcm_out.pcm", "w");
if((pContext->PcmInPtr == NULL)||
(pContext->PcmOutPtr == NULL)){
return -EINVAL;
}
#endif
pContext->InFrames32 = (LVM_INT32 *)malloc(LVREV_MAX_FRAME_SIZE * sizeof(LVM_INT32) * 2);
pContext->OutFrames32 = (LVM_INT32 *)malloc(LVREV_MAX_FRAME_SIZE * sizeof(LVM_INT32) * 2);
ALOGV("\tEffectCreate %p, size %zu", pContext, sizeof(ReverbContext));
ALOGV("\tEffectCreate end\n");
return 0;
} /* end EffectCreate */
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ext4_prepare_context(struct inode *inode)
{
return ext4_convert_inline_data(inode);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DefragReverseSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
if (IPV4_GET_HLEN(reassembled) != 20)
goto end;
if (IPV4_GET_IPLEN(reassembled) != 39)
goto end;
/* 20 bytes in we should find 8 bytes of A. */
for (i = 20; i < 20 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 28; i < 28 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 36; i < 36 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
CWE ID: CWE-358
Target: 1
Example 2:
Code: void Release(int old_route_id) {
session_storage_namespaces_awaiting_close_->erase(old_route_id);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
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;
}
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
flist[i] = NULL;
}
}
*actualCount = count;
for (names = list+1; *names; names++)
Xfree (*names);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void __rtnl_kill_links(struct net *net, struct rtnl_link_ops *ops)
{
struct net_device *dev;
LIST_HEAD(list_kill);
for_each_netdev(net, dev) {
if (dev->rtnl_link_ops == ops)
ops->dellink(dev, &list_kill);
}
unregister_netdevice_many(&list_kill);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: iakerb_alloc_context(iakerb_ctx_id_t *pctx)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
CWE ID: CWE-18
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WallpaperManagerBase::LoadWallpaper(
const AccountId& account_id,
const WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish) {
base::FilePath wallpaper_dir;
base::FilePath wallpaper_path;
if (info.type == ONLINE || info.type == DEFAULT) {
if (info.location.empty()) {
if (base::SysInfo::IsRunningOnChromeOS()) {
NOTREACHED() << "User wallpaper info appears to be broken: "
<< account_id.Serialize();
} else {
LOG(WARNING) << "User wallpaper info is empty: "
<< account_id.Serialize();
return;
}
}
}
if (info.type == ONLINE) {
std::string file_name = GURL(info.location).ExtractFileName();
WallpaperResolution resolution = GetAppropriateResolution();
if (info.layout != WALLPAPER_LAYOUT_STRETCH &&
resolution == WALLPAPER_RESOLUTION_SMALL) {
file_name = base::FilePath(file_name)
.InsertBeforeExtension(kSmallWallpaperSuffix)
.value();
}
DCHECK(dir_chromeos_wallpapers_path_id != -1);
CHECK(PathService::Get(dir_chromeos_wallpapers_path_id,
&wallpaper_dir));
wallpaper_path = wallpaper_dir.Append(file_name);
CustomWallpaperMap::iterator it = wallpaper_cache_.find(account_id);
if (it != wallpaper_cache_.end() &&
it->second.first == wallpaper_path &&
!it->second.second.isNull())
return;
loaded_wallpapers_for_test_++;
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else if (info.type == DEFAULT) {
base::FilePath user_data_dir;
DCHECK(dir_user_data_path_id != -1);
PathService::Get(dir_user_data_path_id, &user_data_dir);
wallpaper_path = user_data_dir.Append(info.location);
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else {
LOG(ERROR) << "Wallpaper reverts to default unexpected.";
DoSetDefaultWallpaper(account_id, std::move(on_finish));
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void WebGLRenderingContextBase::framebufferRenderbuffer(
GLenum target,
GLenum attachment,
GLenum renderbuffertarget,
WebGLRenderbuffer* buffer) {
if (isContextLost() || !ValidateFramebufferFuncParameters(
"framebufferRenderbuffer", target, attachment))
return;
if (renderbuffertarget != GL_RENDERBUFFER) {
SynthesizeGLError(GL_INVALID_ENUM, "framebufferRenderbuffer",
"invalid target");
return;
}
if (buffer && (!buffer->HasEverBeenBound() ||
!buffer->Validate(ContextGroup(), this))) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer",
"buffer never bound or buffer not from this context");
return;
}
WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target);
if (!framebuffer_binding || !framebuffer_binding->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer",
"no framebuffer bound");
return;
}
framebuffer_binding->SetAttachmentForBoundFramebuffer(target, attachment,
buffer);
ApplyStencilTest();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const std::string& DownloadItemImpl::GetHash() const { return hash_; }
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void send(node_t *node, node_t *child, byte *fout) {
if (node->parent) {
send(node->parent, node, fout);
}
if (child) {
if (node->right == child) {
add_bit(1, fout);
} else {
add_bit(0, fout);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void openpic_gcr_write(OpenPICState *opp, uint64_t val)
{
bool mpic_proxy = false;
if (val & GCR_RESET) {
openpic_reset(DEVICE(opp));
return;
}
opp->gcr &= ~opp->mpic_mode_mask;
opp->gcr |= val & opp->mpic_mode_mask;
/* Set external proxy mode */
if ((val & opp->mpic_mode_mask) == GCR_MODE_PROXY) {
mpic_proxy = true;
}
ppce500_set_mpic_proxy(mpic_proxy);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 HB_Error Load_ContextPos3( HB_ContextPosFormat3* cpf3,
HB_Stream stream )
{
HB_Error error;
HB_UShort n, count;
HB_UInt cur_offset, new_offset, base_offset;
HB_Coverage* c;
HB_PosLookupRecord* plr;
base_offset = FILE_Pos() - 2L;
if ( ACCESS_Frame( 4L ) )
return error;
cpf3->GlyphCount = GET_UShort();
cpf3->PosCount = GET_UShort();
FORGET_Frame();
cpf3->Coverage = NULL;
count = cpf3->GlyphCount;
if ( ALLOC_ARRAY( cpf3->Coverage, count, HB_Coverage ) )
return error;
c = cpf3->Coverage;
for ( n = 0; n < count; n++ )
{
if ( ACCESS_Frame( 2L ) )
goto Fail2;
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = _HB_OPEN_Load_Coverage( &c[n], stream ) ) != HB_Err_Ok )
goto Fail2;
(void)FILE_Seek( cur_offset );
}
cpf3->PosLookupRecord = NULL;
count = cpf3->PosCount;
if ( ALLOC_ARRAY( cpf3->PosLookupRecord, count, HB_PosLookupRecord ) )
goto Fail2;
plr = cpf3->PosLookupRecord;
if ( ACCESS_Frame( count * 4L ) )
goto Fail1;
for ( n = 0; n < count; n++ )
{
plr[n].SequenceIndex = GET_UShort();
plr[n].LookupListIndex = GET_UShort();
}
FORGET_Frame();
return HB_Err_Ok;
Fail1:
FREE( plr );
Fail2:
for ( n = 0; n < count; n++ )
_HB_OPEN_Free_Coverage( &c[n] );
FREE( c );
return error;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)
{
struct ipv6_txoptions *opt2;
opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);
if (opt2) {
long dif = (char *)opt2 - (char *)opt;
memcpy(opt2, opt, opt->tot_len);
if (opt2->hopopt)
*((char **)&opt2->hopopt) += dif;
if (opt2->dst0opt)
*((char **)&opt2->dst0opt) += dif;
if (opt2->dst1opt)
*((char **)&opt2->dst1opt) += dif;
if (opt2->srcrt)
*((char **)&opt2->srcrt) += dif;
}
return opt2;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void WebRuntimeFeatures::EnableRemotePlaybackAPI(bool enable) {
RuntimeEnabledFeatures::SetRemotePlaybackEnabled(enable);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 g_timeval_cmp(const GTimeVal *tv1, const GTimeVal *tv2)
{
if (tv1->tv_sec < tv2->tv_sec)
return -1;
if (tv1->tv_sec > tv2->tv_sec)
return 1;
return tv1->tv_usec < tv2->tv_usec ? -1 :
tv1->tv_usec > tv2->tv_usec ? 1 : 0;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: header_put_be_3byte (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)
{ psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_3byte */
CWE ID: CWE-119
Target: 1
Example 2:
Code: PaintLayerScrollableArea::ConvertFromContainingEmbeddedContentViewToScrollbar(
const Scrollbar& scrollbar,
const IntPoint& parent_point) const {
LayoutView* view = GetLayoutBox()->View();
if (!view)
return parent_point;
IntPoint point = view->GetFrameView()->ConvertToLayoutObject(*GetLayoutBox(),
parent_point);
point.Move(-ScrollbarOffset(scrollbar));
return point;
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 DownloadManagerImpl::SetNextId(uint32_t next_id) {
if (next_id > next_download_id_)
next_download_id_ = next_id;
if (!IsNextIdInitialized())
return;
for (auto& callback : id_callbacks_)
std::move(*callback).Run(next_download_id_++);
id_callbacks_.clear();
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void registerBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->blobData.release());
}
CWE ID:
Target: 1
Example 2:
Code: SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
{
if (ses->sectype != Kerberos && ses->sectype != RawNTLMSSP)
ses->sectype = RawNTLMSSP;
switch (ses->sectype) {
case Kerberos:
sess_data->func = SMB2_auth_kerberos;
break;
case RawNTLMSSP:
sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
break;
default:
cifs_dbg(VFS, "secType %d not supported!\n", ses->sectype);
return -EOPNOTSUPP;
}
return 0;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 AppCacheBackendImpl::SelectCacheForSharedWorker(
int host_id, int64 appcache_id) {
AppCacheHost* host = GetHost(host_id);
if (!host || host->was_select_cache_called())
return false;
host->SelectCacheForSharedWorker(appcache_id);
return true;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: SWFShape_setLineStyle2filled_internal(SWFShape shape, unsigned short width,
SWFFillStyle fill,
int flags, float miterLimit)
{
int line;
if ( shape->isEnded )
return;
for ( line=0; line<shape->nLines; ++line )
{
if ( SWFLineStyle_equals2filled(shape->lines[line], width, fill, flags) )
break;
}
if ( line == shape->nLines )
line = SWFShape_addLineStyle2filled(shape, width, fill, flags, miterLimit);
else
++line;
finishSetLine(shape, line, width);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void Ins_GETINFO( INS_ARG )
{
Long K;
K = 0;
/* We return then Windows 3.1 version number */
/* for the font scaler */
if ( (args[0] & 1) != 0 )
K = 3;
/* Has the glyph been rotated ? */
if ( CUR.metrics.rotated )
K |= 0x80;
/* Has the glyph been stretched ? */
if ( CUR.metrics.stretched )
K |= 0x100;
args[0] = K;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE omx_video::empty_this_buffer_proxy(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
(void)hComp;
OMX_U8 *pmem_data_buf = NULL;
int push_cnt = 0;
unsigned nBufIndex = 0;
OMX_ERRORTYPE ret = OMX_ErrorNone;
encoder_media_buffer_type *media_buffer = NULL;
#ifdef _MSM8974_
int fd = 0;
#endif
DEBUG_PRINT_LOW("ETBProxy: buffer->pBuffer[%p]", buffer->pBuffer);
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid buffer[%p]", buffer);
return OMX_ErrorBadParameter;
}
if (meta_mode_enable && !mUsesColorConversion) {
bool met_error = false;
nBufIndex = buffer - meta_buffer_hdr;
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid meta-bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
media_buffer = (encoder_media_buffer_type *)meta_buffer_hdr[nBufIndex].pBuffer;
if (media_buffer) {
if (media_buffer->buffer_type != kMetadataBufferTypeCameraSource &&
media_buffer->buffer_type != kMetadataBufferTypeGrallocSource) {
met_error = true;
} else {
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
if (media_buffer->meta_handle == NULL)
met_error = true;
else if ((media_buffer->meta_handle->numFds != 1 &&
media_buffer->meta_handle->numInts != 2))
met_error = true;
}
}
} else
met_error = true;
if (met_error) {
DEBUG_PRINT_ERROR("ERROR: Unkown source/metahandle in ETB call");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else {
nBufIndex = buffer - ((OMX_BUFFERHEADERTYPE *)m_inp_mem_ptr);
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
}
pending_input_buffers++;
if (input_flush_progress == true) {
post_event ((unsigned long)buffer,0,
OMX_COMPONENT_GENERATE_EBD);
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Input flush in progress");
return OMX_ErrorNone;
}
#ifdef _MSM8974_
if (!meta_mode_enable) {
fd = m_pInput_pmem[nBufIndex].fd;
}
#endif
#ifdef _ANDROID_ICS_
if (meta_mode_enable && !mUseProxyColorFormat) {
struct pmem Input_pmem_info;
if (!media_buffer) {
DEBUG_PRINT_ERROR("%s: invalid media_buffer",__FUNCTION__);
return OMX_ErrorBadParameter;
}
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = media_buffer->meta_handle->data[0];
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = media_buffer->meta_handle->data[1];
Input_pmem_info.size = media_buffer->meta_handle->data[2];
DEBUG_PRINT_LOW("ETB (meta-Camera) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
} else {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = handle->fd;
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = 0;
Input_pmem_info.size = handle->size;
DEBUG_PRINT_LOW("ETB (meta-gralloc) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
}
if (dev_use_buf(&Input_pmem_info,PORT_INDEX_IN,0) != true) {
DEBUG_PRINT_ERROR("ERROR: in dev_use_buf");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (meta_mode_enable && !mUsesColorConversion) {
if (media_buffer->buffer_type == kMetadataBufferTypeGrallocSource) {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
fd = handle->fd;
DEBUG_PRINT_LOW("ETB (opaque-gralloc) fd = %d, size = %d",
fd, handle->size);
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid bufferType for buffer with Opaque"
" color format");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (input_use_buffer && !m_use_input_pmem)
#else
if (input_use_buffer && !m_use_input_pmem)
#endif
{
DEBUG_PRINT_LOW("Heap UseBuffer case, so memcpy the data");
pmem_data_buf = (OMX_U8 *)m_pInput_pmem[nBufIndex].buffer;
memcpy (pmem_data_buf, (buffer->pBuffer + buffer->nOffset),
buffer->nFilledLen);
DEBUG_PRINT_LOW("memcpy() done in ETBProxy for i/p Heap UseBuf");
} else if (mUseProxyColorFormat) {
fd = m_pInput_pmem[nBufIndex].fd;
DEBUG_PRINT_LOW("ETB (color-converted) fd = %d, size = %u",
fd, (unsigned int)buffer->nFilledLen);
} else if (m_sInPortDef.format.video.eColorFormat ==
OMX_COLOR_FormatYUV420SemiPlanar) {
if (!dev_color_align(buffer, m_sInPortDef.format.video.nFrameWidth,
m_sInPortDef.format.video.nFrameHeight)) {
DEBUG_PRINT_ERROR("Failed to adjust buffer color");
post_event((unsigned long)buffer, 0, OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorUndefined;
}
}
#ifdef _MSM8974_
if (dev_empty_buf(buffer, pmem_data_buf,nBufIndex,fd) != true)
#else
if (dev_empty_buf(buffer, pmem_data_buf,0,0) != true)
#endif
{
DEBUG_PRINT_ERROR("ERROR: ETBProxy: dev_empty_buf failed");
#ifdef _ANDROID_ICS_
omx_release_meta_buffer(buffer);
#endif
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
/*Generate an async error and move to invalid state*/
pending_input_buffers--;
if (hw_overload) {
return OMX_ErrorInsufficientResources;
}
return OMX_ErrorBadParameter;
}
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: zcallendpage(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
gx_device *dev = gs_currentdevice(igs);
int code;
check_type(op[-1], t_integer);
check_type(*op, t_integer);
if ((dev = (*dev_proc(dev, get_page_device))(dev)) != 0) {
code = (*dev->page_procs.end_page)(dev, (int)op->value.intval, igs);
if (code < 0)
return code;
if (code > 1)
return_error(gs_error_rangecheck);
} else {
code = (op->value.intval == 2 ? 0 : 1);
}
make_bool(op - 1, code);
pop(1);
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
int result;
handle_t *handle = NULL;
struct super_block *sb = file_inode(vma->vm_file)->i_sb;
bool write = vmf->flags & FAULT_FLAG_WRITE;
if (write) {
sb_start_pagefault(sb);
file_update_time(vma->vm_file);
handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
EXT4_DATA_TRANS_BLOCKS(sb));
}
if (IS_ERR(handle))
result = VM_FAULT_SIGBUS;
else
result = __dax_fault(vma, vmf, ext4_get_block_dax,
ext4_end_io_unwritten);
if (write) {
if (!IS_ERR(handle))
ext4_journal_stop(handle);
sb_end_pagefault(sb);
}
return result;
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SharedMemoryHandleProvider::InitFromMojoHandle(
mojo::ScopedSharedBufferHandle buffer_handle) {
#if DCHECK_IS_ON()
DCHECK_EQ(map_ref_count_, 0);
#endif
DCHECK(!shared_memory_);
base::SharedMemoryHandle memory_handle;
const MojoResult result =
mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle,
&mapped_size_, &read_only_flag_);
if (result != MOJO_RESULT_OK)
return false;
shared_memory_.emplace(memory_handle, read_only_flag_);
return true;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void TaskService::PostBoundTask(RunnerId runner_id, base::OnceClosure task) {
InstanceId instance_id;
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return;
instance_id = bound_instance_id_;
}
GetTaskRunner(runner_id)->PostTask(
FROM_HERE, base::BindOnce(&TaskService::RunTask, base::Unretained(this),
instance_id, runner_id, std::move(task)));
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true);
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void PushMessagingServiceImpl::OnMessagesDeleted(const std::string& app_id) {
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
struct address_space *mapping = inode->i_mapping;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + len - 1);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT |
EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
/*
* If we have a partial block after EOF we have to allocate
* the entire block.
*/
if (partial_end)
max_blocks += 1;
}
if (max_blocks > 0) {
/* Now release the pages and zero block aligned part of pages*/
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
if (ret)
goto out_dio;
/*
* Remove entire range from the extent status tree.
*
* ext4_es_remove_extent(inode, lblk, max_blocks) is
* NOT sufficient. I'm not sure why this is the case,
* but let's be conservative and remove the extent
* status tree for the entire inode. There should be
* no outstanding delalloc extents thanks to the
* filemap_write_and_wait_range() call above.
*/
ret = ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
CWE ID: CWE-17
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_DH
DH *dh_clnt = NULL;
const BIGNUM *pub_key;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
dh_clnt = EVP_PKEY_get0_DH(ckey);
if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(ckey);
return 0;
}
/* send off the data */
DH_get0_key(dh_clnt, &pub_key, NULL);
*len = BN_num_bytes(pub_key);
s2n(*len, *p);
BN_bn2bin(pub_key, *p);
*len += 2;
EVP_PKEY_free(ckey);
return 1;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: xfs_attr_node_removename(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, forkoff;
trace_xfs_attr_node_removename(args);
/*
* Tie a string around our finger to remind us where we are.
*/
dp = args->dp;
state = xfs_da_state_alloc();
state->args = args;
state->mp = dp->i_mount;
/*
* Search to see if name exists, and get back a pointer to it.
*/
error = xfs_da3_node_lookup_int(state, &retval);
if (error || (retval != -EEXIST)) {
if (error == 0)
error = retval;
goto out;
}
/*
* If there is an out-of-line value, de-allocate the blocks.
* This is done before we remove the attribute so that we don't
* overflow the maximum size of a transaction and/or hit a deadlock.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->bp != NULL);
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
if (args->rmtblkno > 0) {
/*
* Fill in disk block numbers in the state structure
* so that we can get the buffers back after we commit
* several transactions in the following calls.
*/
error = xfs_attr_fillstate(state);
if (error)
goto out;
/*
* Mark the attribute as INCOMPLETE, then bunmapi() the
* remote value.
*/
error = xfs_attr3_leaf_setflag(args);
if (error)
goto out;
error = xfs_attr_rmtval_remove(args);
if (error)
goto out;
/*
* Refill the state structure with buffers, the prior calls
* released our buffers.
*/
error = xfs_attr_refillstate(state);
if (error)
goto out;
}
/*
* Remove the name and update the hashvals in the tree.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
retval = xfs_attr3_leaf_remove(blk->bp, args);
xfs_da3_fixhashpath(state, &state->path);
/*
* Check to see if the tree needs to be collapsed.
*/
if (retval && (state->path.active > 1)) {
xfs_defer_init(args->dfops, args->firstblock);
error = xfs_da3_join(state);
if (error)
goto out_defer_cancel;
xfs_defer_ijoin(args->dfops, dp);
error = xfs_defer_finish(&args->trans, args->dfops);
if (error)
goto out_defer_cancel;
/*
* Commit the Btree join operation and start a new trans.
*/
error = xfs_trans_roll_inode(&args->trans, dp);
if (error)
goto out;
}
/*
* If the result is small enough, push it all into the inode.
*/
if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
/*
* Have to get rid of the copy of this dabuf in the state.
*/
ASSERT(state->path.active == 1);
ASSERT(state->path.blk[0].bp);
state->path.blk[0].bp = NULL;
error = xfs_attr3_leaf_read(args->trans, args->dp, 0, -1, &bp);
if (error)
goto out;
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_defer_init(args->dfops, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (error)
goto out_defer_cancel;
xfs_defer_ijoin(args->dfops, dp);
error = xfs_defer_finish(&args->trans, args->dfops);
if (error)
goto out_defer_cancel;
} else
xfs_trans_brelse(args->trans, bp);
}
error = 0;
out:
xfs_da_state_free(state);
return error;
out_defer_cancel:
xfs_defer_cancel(args->dfops);
goto out;
}
CWE ID: CWE-754
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 IsValidURL(const GURL& url, PortPermission port_permission) {
return url.is_valid() && url.SchemeIsHTTPOrHTTPS() &&
(url.port().empty() || (port_permission == ALLOW_NON_STANDARD_PORTS));
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void pipe_advance(struct iov_iter *i, size_t size)
{
struct pipe_inode_info *pipe = i->pipe;
struct pipe_buffer *buf;
int idx = i->idx;
size_t off = i->iov_offset, orig_sz;
if (unlikely(i->count < size))
size = i->count;
orig_sz = size;
if (size) {
if (off) /* make it relative to the beginning of buffer */
size += off - pipe->bufs[idx].offset;
while (1) {
buf = &pipe->bufs[idx];
if (size <= buf->len)
break;
size -= buf->len;
idx = next_idx(idx, pipe);
}
buf->len = size;
i->idx = idx;
off = i->iov_offset = buf->offset + size;
}
if (off)
idx = next_idx(idx, pipe);
if (pipe->nrbufs) {
int unused = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
/* [curbuf,unused) is in use. Free [idx,unused) */
while (idx != unused) {
pipe_buf_release(pipe, &pipe->bufs[idx]);
idx = next_idx(idx, pipe);
pipe->nrbufs--;
}
}
i->count -= orig_sz;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLLinkElement::DidSendLoadForLinkPrerender() {
DispatchEvent(*Event::Create(EventTypeNames::webkitprerenderload));
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 GLES2DecoderImpl::SimulateFixedAttribs(
const char* function_name,
GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
if (!vertex_attrib_manager_->HaveFixedAttribs()) {
return true;
}
PerformanceWarning(
"GL_FIXED attributes have a signficant performance penalty");
GLuint elements_needed = 0;
const VertexAttribManager::VertexAttribInfoList& infos =
vertex_attrib_manager_->GetEnabledVertexAttribInfos();
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
GLuint elements_used = 0;
if (!SafeMultiply(num_vertices,
static_cast<GLuint>(info->size()), &elements_used) ||
!SafeAdd(elements_needed, elements_used, &elements_needed)) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
}
const GLuint kSizeOfFloat = sizeof(float); // NOLINT
GLuint size_needed = 0;
if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_);
if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
GLintptr offset = 0;
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
int num_elements = info->size() * kSizeOfFloat;
int size = num_elements * num_vertices;
scoped_array<float> data(new float[size]);
const int32* src = reinterpret_cast<const int32 *>(
info->buffer()->GetRange(info->offset(), size));
const int32* end = src + num_elements;
float* dst = data.get();
while (src != end) {
*dst++ = static_cast<float>(*src++) / 65536.0f;
}
glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get());
glVertexAttribPointer(
info->index(), info->size(), GL_FLOAT, false, 0,
reinterpret_cast<GLvoid*>(offset));
offset += size;
}
}
*simulated = true;
return true;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!indexed_db_observer_) {
indexed_db_observer_ = std::make_unique<IndexedDBObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<IndexedDBContextImpl*>(
process_->GetStoragePartition()->GetIndexedDBContext()));
}
return indexed_db_observer_.get();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static s32 atl2_setup_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int size;
u8 offset = 0;
/* real ring DMA buffer */
adapter->ring_size = size =
adapter->txd_ring_size * 1 + 7 + /* dword align */
adapter->txs_ring_size * 4 + 7 + /* dword align */
adapter->rxd_ring_size * 1536 + 127; /* 128bytes align */
adapter->ring_vir_addr = pci_alloc_consistent(pdev, size,
&adapter->ring_dma);
if (!adapter->ring_vir_addr)
return -ENOMEM;
memset(adapter->ring_vir_addr, 0, adapter->ring_size);
/* Init TXD Ring */
adapter->txd_dma = adapter->ring_dma ;
offset = (adapter->txd_dma & 0x7) ? (8 - (adapter->txd_dma & 0x7)) : 0;
adapter->txd_dma += offset;
adapter->txd_ring = adapter->ring_vir_addr + offset;
/* Init TXS Ring */
adapter->txs_dma = adapter->txd_dma + adapter->txd_ring_size;
offset = (adapter->txs_dma & 0x7) ? (8 - (adapter->txs_dma & 0x7)) : 0;
adapter->txs_dma += offset;
adapter->txs_ring = (struct tx_pkt_status *)
(((u8 *)adapter->txd_ring) + (adapter->txd_ring_size + offset));
/* Init RXD Ring */
adapter->rxd_dma = adapter->txs_dma + adapter->txs_ring_size * 4;
offset = (adapter->rxd_dma & 127) ?
(128 - (adapter->rxd_dma & 127)) : 0;
if (offset > 7)
offset -= 8;
else
offset += (128 - 8);
adapter->rxd_dma += offset;
adapter->rxd_ring = (struct rx_desc *) (((u8 *)adapter->txs_ring) +
(adapter->txs_ring_size * 4 + offset));
/*
* Read / Write Ptr Initialize:
* init_ring_ptrs(adapter);
*/
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 ResolveRelativeURL(const char* base_url,
const url_parse::Parsed& base_parsed,
bool base_is_file,
const base::char16* relative_url,
const url_parse::Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
url_parse::Parsed* out_parsed) {
return DoResolveRelativeURL<base::char16>(
base_url, base_parsed, base_is_file, relative_url,
relative_component, query_converter, output, out_parsed);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *hashtable_get(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return pair->value;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: void PDFiumEngine::StopFind() {
SelectionChangeInvalidator selection_invalidator(this);
selection_.clear();
selecting_ = false;
find_results_.clear();
next_page_to_search_ = -1;
last_page_to_search_ = -1;
last_character_index_to_search_ = -1;
current_find_index_.Invalidate();
current_find_text_.clear();
UpdateTickMarks();
find_factory_.CancelAll();
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void cpuacct_update_stats(struct task_struct *tsk,
enum cpuacct_stat_index idx, cputime_t val) {}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Cluster* Cluster::Create(
Segment* pSegment,
long idx,
long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment,
idx,
element_start);
assert(pCluster);
return pCluster;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebKitTestResultPrinter::PrintAudioFooter() {
if (state_ != IN_AUDIO_BLOCK)
return;
if (!capture_text_only_) {
*output_ << "#EOF\n";
output_->flush();
}
state_ = IN_IMAGE_BLOCK;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 Browser::UnregisterKeepAlive() {
keep_alive_.reset();
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
cJSON *current_element = NULL;
if ((object == NULL) || (name == NULL))
{
return NULL;
}
current_element = object->child;
if (case_sensitive)
{
while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
{
current_element = current_element->next;
}
}
else
{
while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
{
current_element = current_element->next;
}
}
return current_element;
}
CWE ID: CWE-754
Target: 1
Example 2:
Code: gdImagePtr gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
{
gdImagePtr im;
gdIOCtx *in = gdNewFileCtx(inFile);
im = gdImageCreateFromGd2PartCtx(in, srcx, srcy, w, h);
in->gd_free(in);
return im;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 CameraSource::releaseQueuedFrames() {
List<sp<IMemory> >::iterator it;
while (!mFramesReceived.empty()) {
it = mFramesReceived.begin();
releaseRecordingFrame(*it);
mFramesReceived.erase(it);
++mNumFramesDropped;
}
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb->sk = sk;
llc_sap_state_process(sap, skb);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == QuantumRange)
return(MagickTrue);
image->matte=MagickTrue;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity)));
else if (opacity > 0)
SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/
(MagickRealType) opacity)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
CWE ID: CWE-834
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 complete_emulated_mmio(struct kvm_vcpu *vcpu)
{
struct kvm_run *run = vcpu->run;
struct kvm_mmio_fragment *frag;
unsigned len;
BUG_ON(!vcpu->mmio_needed);
/* Complete previous fragment */
frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
len = min(8u, frag->len);
if (!vcpu->mmio_is_write)
memcpy(frag->data, run->mmio.data, len);
if (frag->len <= 8) {
/* Switch to the next fragment. */
frag++;
vcpu->mmio_cur_fragment++;
} else {
/* Go forward to the next mmio piece. */
frag->data += len;
frag->gpa += len;
frag->len -= len;
}
if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
vcpu->mmio_needed = 0;
/* FIXME: return into emulator if single-stepping. */
if (vcpu->mmio_is_write)
return 1;
vcpu->mmio_read_completed = 1;
return complete_emulated_io(vcpu);
}
run->exit_reason = KVM_EXIT_MMIO;
run->mmio.phys_addr = frag->gpa;
if (vcpu->mmio_is_write)
memcpy(run->mmio.data, frag->data, min(8u, frag->len));
run->mmio.len = min(8u, frag->len);
run->mmio.is_write = vcpu->mmio_is_write;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
return 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothOptionsHandler::RequestConfirmation(
chromeos::BluetoothDevice* device,
int passkey) {
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void intel_pmu_cpu_starting(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
int core_id = topology_core_id(cpu);
int i;
init_debug_store_on_cpu(cpu);
/*
* Deal with CPUs that don't clear their LBRs on power-up.
*/
intel_pmu_lbr_reset();
if (!cpu_has_ht_siblings())
return;
for_each_cpu(i, topology_thread_cpumask(cpu)) {
struct intel_percore *pc = per_cpu(cpu_hw_events, i).per_core;
if (pc && pc->core_id == core_id) {
kfree(cpuc->per_core);
cpuc->per_core = pc;
break;
}
}
cpuc->per_core->core_id = core_id;
cpuc->per_core->refcnt++;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 SplashOutputDev::drawMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr, int maskWidth,
int maskHeight, GBool maskInvert) {
GfxImageColorMap *maskColorMap;
Object maskDecode, decodeLow, decodeHigh;
double *ctm;
SplashCoord mat[6];
SplashOutMaskedImageData imgData;
SplashOutImageMaskData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
if (maskWidth > width || maskHeight > height) {
decodeLow.initInt(maskInvert ? 0 : 1);
decodeHigh.initInt(maskInvert ? 1 : 0);
maskDecode.initArray(xref);
maskDecode.arrayAdd(&decodeLow);
maskDecode.arrayAdd(&decodeHigh);
maskColorMap = new GfxImageColorMap(1, &maskDecode,
new GfxDeviceGrayColorSpace());
maskDecode.free();
drawSoftMaskedImage(state, ref, str, width, height, colorMap,
maskStr, maskWidth, maskHeight, maskColorMap);
delete maskColorMap;
} else {
mat[0] = (SplashCoord)width;
mat[1] = 0;
mat[2] = 0;
mat[3] = (SplashCoord)height;
mat[4] = 0;
mat[5] = 0;
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth, 1, 1);
imgMaskData.imgStr->reset();
imgMaskData.invert = maskInvert ? 0 : 1;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
maskBitmap = new SplashBitmap(width, height, 1, splashModeMono1, gFalse);
maskSplash = new Splash(maskBitmap, gFalse);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskColor[0] = 0xff;
maskSplash->setFillPattern(new SplashSolidColor(maskColor));
maskSplash->fillImageMask(&imageMaskSrc, &imgMaskData,
maskWidth, maskHeight, mat, gFalse);
delete imgMaskData.imgStr;
maskStr->close();
delete maskSplash;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.mask = maskBitmap;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&maskedImageSrc, &imgData, srcMode, gTrue,
width, height, mat);
delete maskBitmap;
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
struct cifs_ses *ses)
{
NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
__u32 flags;
memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmNegotiate;
/* BB is NTLMV2 session security format easier to use here? */
flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;
if (ses->server->sign) {
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab ||
ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
}
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->WorkstationName.BufferOffset = 0;
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
sec_blob->DomainName.BufferOffset = 0;
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int opl3_kill_note (int devno, int voice, int note, int velocity)
{
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return 0;
devc->v_alloc->map[voice] = 0;
map = &pv_map[devc->lv_map[voice]];
DEB(printk("Kill note %d\n", voice));
if (map->voice_mode == 0)
return 0;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, devc->voc[voice].keyon_byte & ~0x20);
devc->voc[voice].keyon_byte = 0;
devc->voc[voice].bender = 0;
devc->voc[voice].volume = 64;
devc->voc[voice].panning = 0xffff; /* Not set */
devc->voc[voice].bender_range = 200;
devc->voc[voice].orig_freq = 0;
devc->voc[voice].current_freq = 0;
devc->voc[voice].mode = 0;
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
ext4_lblk_t num, ext_prepare_callback func,
void *cbdata)
{
struct ext4_ext_path *path = NULL;
struct ext4_ext_cache cbex;
struct ext4_extent *ex;
ext4_lblk_t next, start = 0, end = 0;
ext4_lblk_t last = block + num;
int depth, exists, err = 0;
BUG_ON(func == NULL);
BUG_ON(inode == NULL);
while (block < last && block != EXT_MAX_BLOCKS) {
num = last - block;
/* find extent for this block */
down_read(&EXT4_I(inode)->i_data_sem);
path = ext4_ext_find_extent(inode, block, path);
up_read(&EXT4_I(inode)->i_data_sem);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
break;
}
depth = ext_depth(inode);
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
err = -EIO;
break;
}
ex = path[depth].p_ext;
next = ext4_ext_next_allocated_block(path);
exists = 0;
if (!ex) {
/* there is no extent yet, so try to allocate
* all requested space */
start = block;
end = block + num;
} else if (le32_to_cpu(ex->ee_block) > block) {
/* need to allocate space before found extent */
start = block;
end = le32_to_cpu(ex->ee_block);
if (block + num < end)
end = block + num;
} else if (block >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
/* need to allocate space after found extent */
start = block;
end = block + num;
if (end >= next)
end = next;
} else if (block >= le32_to_cpu(ex->ee_block)) {
/*
* some part of requested space is covered
* by found extent
*/
start = block;
end = le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex);
if (block + num < end)
end = block + num;
exists = 1;
} else {
BUG();
}
BUG_ON(end <= start);
if (!exists) {
cbex.ec_block = start;
cbex.ec_len = end - start;
cbex.ec_start = 0;
} else {
cbex.ec_block = le32_to_cpu(ex->ee_block);
cbex.ec_len = ext4_ext_get_actual_len(ex);
cbex.ec_start = ext4_ext_pblock(ex);
}
if (unlikely(cbex.ec_len == 0)) {
EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
err = -EIO;
break;
}
err = func(inode, next, &cbex, ex, cbdata);
ext4_ext_drop_refs(path);
if (err < 0)
break;
if (err == EXT_REPEAT)
continue;
else if (err == EXT_BREAK) {
err = 0;
break;
}
if (ext_depth(inode) != depth) {
/* depth was changed. we have to realloc path */
kfree(path);
path = NULL;
}
block = cbex.ec_block + cbex.ec_len;
}
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err;
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned char mincore_page(struct address_space *mapping, pgoff_t pgoff)
{
unsigned char present = 0;
struct page *page;
/*
* When tmpfs swaps out a page from a file, any process mapping that
* file will not get a swp_entry_t in its pte, but rather it is like
* any other file mapping (ie. marked !present and faulted in with
* tmpfs's .fault). So swapped out tmpfs mappings are tested here.
*/
#ifdef CONFIG_SWAP
if (shmem_mapping(mapping)) {
page = find_get_entry(mapping, pgoff);
/*
* shmem/tmpfs may return swap: account for swapcache
* page too.
*/
if (xa_is_value(page)) {
swp_entry_t swp = radix_to_swp_entry(page);
page = find_get_page(swap_address_space(swp),
swp_offset(swp));
}
} else
page = find_get_page(mapping, pgoff);
#else
page = find_get_page(mapping, pgoff);
#endif
if (page) {
present = PageUptodate(page);
put_page(page);
}
return present;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: PHP_FUNCTION(imagecolorstotal)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorsTotal(im));
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 PrintPreviewMessageHandler::OnDidPreviewPage(
const PrintHostMsg_DidPreviewPage_Params& params) {
int page_number = params.page_number;
if (page_number < FIRST_PAGE_INDEX || !params.data_size)
return;
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
scoped_refptr<base::RefCountedBytes> data_bytes =
GetDataFromHandle(params.metafile_data_handle, params.data_size);
DCHECK(data_bytes);
print_preview_ui->SetPrintPreviewDataForIndex(page_number,
std::move(data_bytes));
print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id);
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool BaseSettingChange::Init(Profile* profile) {
DCHECK(profile);
profile_ = profile;
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: find_check_entry(struct ip6t_entry *e, struct net *net, const char *name,
unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
unsigned int j;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ipv6;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV6;
xt_ematch_foreach(ematch, e) {
ret = find_check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
t = ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto cleanup_matches;
}
t->u.kernel.target = target;
ret = check_target(e, net, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
const content::NavigationEntry* entry =
source->GetController().GetActiveEntry();
if (entry) {
const GURL& url = entry->GetURL();
const GURL& virtual_url = entry->GetVirtualURL();
if ((url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUINewTabHost) ||
(virtual_url.SchemeIs(content::kChromeUIScheme) &&
virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
return true;
}
}
return search::NavEntryIsInstantNTP(source, entry);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void IOHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_host_ = process_host;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct urb *uas_alloc_sense_urb(struct uas_dev_info *devinfo, gfp_t gfp,
struct scsi_cmnd *cmnd)
{
struct usb_device *udev = devinfo->udev;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct urb *urb = usb_alloc_urb(0, gfp);
struct sense_iu *iu;
if (!urb)
goto out;
iu = kzalloc(sizeof(*iu), gfp);
if (!iu)
goto free;
usb_fill_bulk_urb(urb, udev, devinfo->status_pipe, iu, sizeof(*iu),
uas_stat_cmplt, cmnd->device->host);
if (devinfo->use_streams)
urb->stream_id = cmdinfo->uas_tag;
urb->transfer_flags |= URB_FREE_BUFFER;
out:
return urb;
free:
usb_free_urb(urb);
return NULL;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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::DrawingBufferClientRestoreMaskAndClearValues() {
if (destruction_in_progress_)
return;
if (!ContextGL())
return;
bool color_mask_alpha =
color_mask_[3] && active_scoped_rgb_emulation_color_masks_ == 0;
ContextGL()->ColorMask(color_mask_[0], color_mask_[1], color_mask_[2],
color_mask_alpha);
ContextGL()->DepthMask(depth_mask_);
ContextGL()->StencilMaskSeparate(GL_FRONT, stencil_mask_);
ContextGL()->ClearColor(clear_color_[0], clear_color_[1], clear_color_[2],
clear_color_[3]);
ContextGL()->ClearDepthf(clear_depth_);
ContextGL()->ClearStencil(clear_stencil_);
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: dtls1_process_buffered_records(SSL *s)
{
pitem *item;
item = pqueue_peek(s->d1->unprocessed_rcds.q);
if (item)
{
/* Check if epoch is current. */
if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
return(1); /* Nothing to do. */
/* Process all the records. */
while (pqueue_peek(s->d1->unprocessed_rcds.q))
{
dtls1_get_unprocessed_record(s);
if ( ! dtls1_process_record(s))
return(0);
dtls1_buffer_record(s, &(s->d1->processed_rcds),
s->s3->rrec.seq_num);
}
}
/* sync epoch numbers once all the unprocessed records
* have been processed */
s->d1->processed_rcds.epoch = s->d1->r_epoch;
s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
return(1);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void LocalFrame::DidFreeze() {
DCHECK(RuntimeEnabledFeatures::PageLifecycleEnabled());
if (GetDocument()) {
GetDocument()->DispatchFreezeEvent();
if (auto* frame_resource_coordinator = GetFrameResourceCoordinator()) {
frame_resource_coordinator->SetLifecycleState(
resource_coordinator::mojom::LifecycleState::kFrozen);
}
}
}
CWE ID: CWE-285
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {
jas_eprintf("all tiles are outside the image area\n");
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PepperRendererConnection::OnMsgDidDeleteInProcessInstance(
PP_Instance instance) {
in_process_host_->DeleteInstance(instance);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static dma_addr_t arm_iommu_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
if (!dma_get_attr(DMA_ATTR_SKIP_CPU_SYNC, attrs))
__dma_page_cpu_to_dev(page, offset, size, dir);
return arm_coherent_iommu_map_page(dev, page, offset, size, dir, attrs);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: enum act_parse_ret parse_http_action_reject(const char **args, int *orig_arg, struct proxy *px,
struct act_rule *rule, char **err)
{
rule->action = ACT_CUSTOM;
rule->action_ptr = http_action_reject;
return ACT_RET_PRS_OK;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: MockDataReductionProxyConfig::~MockDataReductionProxyConfig() {
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 emulate_int(struct x86_emulate_ctxt *ctxt, int irq)
{
switch(ctxt->mode) {
case X86EMUL_MODE_REAL:
return __emulate_int_real(ctxt, irq);
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT64:
default:
/* Protected mode interrupts unimplemented yet */
return X86EMUL_UNHANDLEABLE;
}
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: image_transform_set_end(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
UNUSED(this)
UNUSED(that)
UNUSED(pp)
UNUSED(pi)
}
CWE ID:
Target: 1
Example 2:
Code: HeadlessWebContentsImpl* HeadlessWebContentsImpl::From(
HeadlessBrowser* browser,
content::WebContents* contents) {
return HeadlessWebContentsImpl::From(
browser->GetWebContentsForDevToolsAgentHostId(
content::DevToolsAgentHost::GetOrCreateFor(contents)->GetId()));
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 BlinkTestRunner::DeleteAllCookies() {
Send(new LayoutTestHostMsg_DeleteAllCookies(routing_id()));
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ShellWindowFrameView::ShellWindowFrameView()
: frame_(NULL),
close_button_(NULL) {
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: void PPB_URLLoader_Impl::willSendRequest(
WebURLLoader* loader,
WebURLRequest& new_request,
const WebURLResponse& redirect_response) {
if (!request_info_->follow_redirects()) {
SaveResponse(redirect_response);
loader_->setDefersLoading(true);
RunCallback(PP_OK);
}
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 sctp_setsockopt_context(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assoc_value))
return -EINVAL;
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
sp = sctp_sk(sk);
if (params.assoc_id != 0) {
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc)
return -EINVAL;
asoc->default_rcv_context = params.assoc_value;
} else {
sp->default_rcv_context = params.assoc_value;
}
return 0;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int mp_unpack_full(lua_State *L, int limit, int offset) {
size_t len;
const char *s;
mp_cur c;
int cnt; /* Number of objects unpacked */
int decode_all = (!limit && !offset);
s = luaL_checklstring(L,1,&len); /* if no match, exits */
if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
return luaL_error(L,
"Invalid request to unpack with offset of %d and limit of %d.",
offset, len);
else if (offset > len)
return luaL_error(L,
"Start offset %d greater than input length %d.", offset, len);
if (decode_all) limit = INT_MAX;
mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
/* We loop over the decode because this could be a stream
* of multiple top-level values serialized together */
for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
mp_decode_to_lua_type(L,&c);
if (c.err == MP_CUR_ERROR_EOF) {
return luaL_error(L,"Missing bytes in input.");
} else if (c.err == MP_CUR_ERROR_BADFMT) {
return luaL_error(L,"Bad data format in input.");
}
}
if (!decode_all) {
/* c->left is the remaining size of the input buffer.
* subtract the entire buffer size from the unprocessed size
* to get our next start offset */
int offset = len - c.left;
/* Return offset -1 when we have have processed the entire buffer. */
lua_pushinteger(L, c.left == 0 ? -1 : offset);
/* Results are returned with the arg elements still
* in place. Lua takes care of only returning
* elements above the args for us.
* In this case, we have one arg on the stack
* for this function, so we insert our first return
* value at position 2. */
lua_insert(L, 2);
cnt += 1; /* increase return count by one to make room for offset */
}
return cnt;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: s32 hid_snto32(__u32 value, unsigned n)
{
return snto32(value, n);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: AccessibilityExpanded AXNodeObject::isExpanded() const {
if (getNode() && isHTMLSummaryElement(*getNode())) {
if (getNode()->parentNode() &&
isHTMLDetailsElement(getNode()->parentNode()))
return toElement(getNode()->parentNode())->hasAttribute(openAttr)
? ExpandedExpanded
: ExpandedCollapsed;
}
const AtomicString& expanded = getAttribute(aria_expandedAttr);
if (equalIgnoringCase(expanded, "true"))
return ExpandedExpanded;
if (equalIgnoringCase(expanded, "false"))
return ExpandedCollapsed;
return ExpandedUndefined;
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ion_handle_put(struct ion_handle *handle)
{
struct ion_client *client = handle->client;
int ret;
mutex_lock(&client->lock);
ret = kref_put(&handle->ref, ion_handle_destroy);
mutex_unlock(&client->lock);
return ret;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void HTMLCanvasElement::DidMoveToNewDocument(Document& old_document) {
ContextLifecycleObserver::SetContext(&GetDocument());
PageVisibilityObserver::SetContext(GetDocument().GetPage());
HTMLElement::DidMoveToNewDocument(old_document);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void NormalPageArena::SweepAndCompact() {
ThreadHeap& heap = GetThreadState()->Heap();
if (!heap.Compaction()->IsCompactingArena(ArenaIndex()))
return;
if (SweepingCompleted()) {
heap.Compaction()->FinishedArenaCompaction(this, 0, 0);
return;
}
NormalPage::CompactionContext context;
context.compacted_pages_ = &first_page_;
while (!SweepingCompleted()) {
BasePage* page = first_unswept_page_;
if (page->IsEmpty()) {
page->Unlink(&first_unswept_page_);
page->RemoveFromHeap();
continue;
}
DCHECK(!page->IsLargeObjectPage());
NormalPage* normal_page = static_cast<NormalPage*>(page);
normal_page->Unlink(&first_unswept_page_);
normal_page->MarkAsSwept();
if (!context.current_page_)
context.current_page_ = normal_page;
else
normal_page->Link(&context.available_pages_);
normal_page->SweepAndCompact(context);
}
if (!context.current_page_) {
heap.Compaction()->FinishedArenaCompaction(this, 0, 0);
return;
}
size_t freed_size = 0;
size_t freed_page_count = 0;
size_t allocation_point = context.allocation_point_;
if (!allocation_point) {
context.current_page_->Link(&context.available_pages_);
} else {
NormalPage* current_page = context.current_page_;
current_page->Link(&first_page_);
if (allocation_point != current_page->PayloadSize()) {
freed_size = current_page->PayloadSize() - allocation_point;
Address payload = current_page->Payload();
SET_MEMORY_INACCESSIBLE(payload + allocation_point, freed_size);
current_page->ArenaForNormalPage()->AddToFreeList(
payload + allocation_point, freed_size);
}
}
BasePage* available_pages = context.available_pages_;
#if DEBUG_HEAP_COMPACTION
std::stringstream stream;
#endif
while (available_pages) {
size_t page_size = available_pages->size();
#if DEBUG_HEAP_COMPACTION
if (!freed_page_count)
stream << "Releasing:";
stream << " [" << available_pages << ", " << (available_pages + page_size)
<< "]";
#endif
freed_size += page_size;
freed_page_count++;
BasePage* next_page;
available_pages->Unlink(&next_page);
#if !(DCHECK_IS_ON() || defined(LEAK_SANITIZER) || \
defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER))
DCHECK(!available_pages->IsLargeObjectPage());
NormalPage* unused_page = reinterpret_cast<NormalPage*>(available_pages);
memset(unused_page->Payload(), 0, unused_page->PayloadSize());
#endif
available_pages->RemoveFromHeap();
available_pages = static_cast<NormalPage*>(next_page);
}
#if DEBUG_HEAP_COMPACTION
if (freed_page_count)
LOG_HEAP_COMPACTION() << stream.str();
#endif
heap.Compaction()->FinishedArenaCompaction(this, freed_page_count,
freed_size);
VerifyObjectStartBitmap();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
{
struct nlmsghdr *nlh;
int size = nlmsg_msg_size(len);
nlh = (struct nlmsghdr *)skb_put(skb, NLMSG_ALIGN(size));
nlh->nlmsg_type = type;
nlh->nlmsg_len = size;
nlh->nlmsg_flags = flags;
nlh->nlmsg_pid = portid;
nlh->nlmsg_seq = seq;
if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
return nlh;
}
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: create_policy_2_svc(cpol_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;
}
prime_arg = arg->rec.policy;
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_ADD, NULL, NULL)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_policy", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_policy((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_policy",
((prime_arg == NULL) ? "(null)" : prime_arg), errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Browser::OpenUpdateChromeDialog() {
UserMetrics::RecordAction(UserMetricsAction("UpdateChrome"));
window_->ShowUpdateChromeDialog();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cpContigBufToSeparateBuf(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp,
int bytes_per_sample )
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
{
int n = bytes_per_sample;
while( n-- ) {
*out++ = *in++;
}
in += (spp-1) * bytes_per_sample;
}
out += outskew;
in += inskew;
}
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
{
char block_dev[PATH_MAX+1];
size_t size;
unsigned int blksize;
unsigned int blocks;
unsigned int range_count;
unsigned int i;
if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) {
LOGW("failed to read block device from header\n");
return -1;
}
for (i = 0; i < sizeof(block_dev); ++i) {
if (block_dev[i] == '\n') {
block_dev[i] = 0;
break;
}
}
if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) {
LOGW("failed to parse block map header\n");
return -1;
}
blocks = ((size-1) / blksize) + 1;
pMap->range_count = range_count;
pMap->ranges = malloc(range_count * sizeof(MappedRange));
memset(pMap->ranges, 0, range_count * sizeof(MappedRange));
unsigned char* reserve;
reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (reserve == MAP_FAILED) {
LOGW("failed to reserve address space: %s\n", strerror(errno));
return -1;
}
pMap->ranges[range_count-1].addr = reserve;
pMap->ranges[range_count-1].length = blocks * blksize;
int fd = open(block_dev, O_RDONLY);
if (fd < 0) {
LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno));
return -1;
}
unsigned char* next = reserve;
for (i = 0; i < range_count; ++i) {
int start, end;
if (fscanf(mapf, "%d %d\n", &start, &end) != 2) {
LOGW("failed to parse range %d in block map\n", i);
return -1;
}
void* addr = mmap64(next, (end-start)*blksize, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize);
if (addr == MAP_FAILED) {
LOGW("failed to map block %d: %s\n", i, strerror(errno));
return -1;
}
pMap->ranges[i].addr = addr;
pMap->ranges[i].length = (end-start)*blksize;
next += pMap->ranges[i].length;
}
pMap->addr = reserve;
pMap->length = size;
LOGI("mmapped %d ranges\n", range_count);
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline void ext3_show_quota_options(struct seq_file *seq, struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext3_sb_info *sbi = EXT3_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]);
if (test_opt(sb, USRQUOTA))
seq_puts(seq, ",usrquota");
if (test_opt(sb, GRPQUOTA))
seq_puts(seq, ",grpquota");
#endif
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 jsTestObjPrototypeFunctionIntMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = jsNumber(impl->intMethodWithArgs(intArg, strArg, objArg));
return JSValue::encode(result);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ThreadHeap::TakeSnapshot(SnapshotType type) {
DCHECK(thread_state_->InAtomicMarkingPause());
ThreadState::GCSnapshotInfo info(GCInfoTable::GcInfoIndex() + 1);
String thread_dump_name =
String::Format("blink_gc/thread_%lu",
static_cast<unsigned long>(thread_state_->ThreadId()));
const String heaps_dump_name = thread_dump_name + "/heaps";
const String classes_dump_name = thread_dump_name + "/classes";
int number_of_heaps_reported = 0;
#define SNAPSHOT_HEAP(ArenaType) \
{ \
number_of_heaps_reported++; \
switch (type) { \
case SnapshotType::kHeapSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \
heaps_dump_name + "/" #ArenaType, info); \
break; \
case SnapshotType::kFreelistSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \
heaps_dump_name + "/" #ArenaType); \
break; \
default: \
NOTREACHED(); \
} \
}
SNAPSHOT_HEAP(NormalPage1);
SNAPSHOT_HEAP(NormalPage2);
SNAPSHOT_HEAP(NormalPage3);
SNAPSHOT_HEAP(NormalPage4);
SNAPSHOT_HEAP(EagerSweep);
SNAPSHOT_HEAP(Vector1);
SNAPSHOT_HEAP(Vector2);
SNAPSHOT_HEAP(Vector3);
SNAPSHOT_HEAP(Vector4);
SNAPSHOT_HEAP(InlineVector);
SNAPSHOT_HEAP(HashTable);
SNAPSHOT_HEAP(LargeObject);
FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP);
DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas);
#undef SNAPSHOT_HEAP
if (type == SnapshotType::kFreelistSnapshot)
return;
size_t total_live_count = 0;
size_t total_dead_count = 0;
size_t total_live_size = 0;
size_t total_dead_size = 0;
for (size_t gc_info_index = 1; gc_info_index <= GCInfoTable::GcInfoIndex();
++gc_info_index) {
total_live_count += info.live_count[gc_info_index];
total_dead_count += info.dead_count[gc_info_index];
total_live_size += info.live_size[gc_info_index];
total_dead_size += info.dead_size[gc_info_index];
}
base::trace_event::MemoryAllocatorDump* thread_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name);
thread_dump->AddScalar("live_count", "objects", total_live_count);
thread_dump->AddScalar("dead_count", "objects", total_dead_count);
thread_dump->AddScalar("live_size", "bytes", total_live_size);
thread_dump->AddScalar("dead_size", "bytes", total_dead_size);
base::trace_event::MemoryAllocatorDump* heaps_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name);
base::trace_event::MemoryAllocatorDump* classes_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name);
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid());
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static struct zonelist *policy_zonelist(gfp_t gfp, struct mempolicy *policy,
int nd)
{
if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL))
nd = policy->v.preferred_node;
else {
/*
* __GFP_THISNODE shouldn't even be used with the bind policy
* because we might easily break the expectation to stay on the
* requested node and not break the policy.
*/
WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
}
return node_zonelist(nd, gfp);
}
CWE ID: CWE-388
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: transform_image_validate(transform_display *dp, png_const_structp pp,
png_infop pi)
{
/* Constants for the loop below: */
PNG_CONST png_store* PNG_CONST ps = dp->this.ps;
PNG_CONST png_byte in_ct = dp->this.colour_type;
PNG_CONST png_byte in_bd = dp->this.bit_depth;
PNG_CONST png_uint_32 w = dp->this.w;
PNG_CONST png_uint_32 h = dp->this.h;
PNG_CONST png_byte out_ct = dp->output_colour_type;
PNG_CONST png_byte out_bd = dp->output_bit_depth;
PNG_CONST png_byte sample_depth = (png_byte)(out_ct ==
PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
PNG_CONST png_byte red_sBIT = dp->this.red_sBIT;
PNG_CONST png_byte green_sBIT = dp->this.green_sBIT;
PNG_CONST png_byte blue_sBIT = dp->this.blue_sBIT;
PNG_CONST png_byte alpha_sBIT = dp->this.alpha_sBIT;
PNG_CONST int have_tRNS = dp->this.is_transparent;
double digitization_error;
store_palette out_palette;
png_uint_32 y;
UNUSED(pi)
/* Check for row overwrite errors */
store_image_check(dp->this.ps, pp, 0);
/* Read the palette corresponding to the output if the output colour type
* indicates a palette, othewise set out_palette to garbage.
*/
if (out_ct == PNG_COLOR_TYPE_PALETTE)
{
/* Validate that the palette count itself has not changed - this is not
* expected.
*/
int npalette = (-1);
(void)read_palette(out_palette, &npalette, pp, pi);
if (npalette != dp->this.npalette)
png_error(pp, "unexpected change in palette size");
digitization_error = .5;
}
else
{
png_byte in_sample_depth;
memset(out_palette, 0x5e, sizeof out_palette);
/* use-input-precision means assume that if the input has 8 bit (or less)
* samples and the output has 16 bit samples the calculations will be done
* with 8 bit precision, not 16.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
in_sample_depth = 8;
else
in_sample_depth = in_bd;
if (sample_depth != 16 || in_sample_depth > 8 ||
!dp->pm->calculations_use_input_precision)
digitization_error = .5;
/* Else calculations are at 8 bit precision, and the output actually
* consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
*/
else
digitization_error = .5 * 257;
}
for (y=0; y<h; ++y)
{
png_const_bytep PNG_CONST pRow = store_image_row(ps, pp, 0, y);
png_uint_32 x;
/* The original, standard, row pre-transforms. */
png_byte std[STANDARD_ROWMAX];
transform_row(pp, std, in_ct, in_bd, y);
/* Go through each original pixel transforming it and comparing with what
* libpng did to the same pixel.
*/
for (x=0; x<w; ++x)
{
image_pixel in_pixel, out_pixel;
unsigned int r, g, b, a;
/* Find out what we think the pixel should be: */
image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette);
in_pixel.red_sBIT = red_sBIT;
in_pixel.green_sBIT = green_sBIT;
in_pixel.blue_sBIT = blue_sBIT;
in_pixel.alpha_sBIT = alpha_sBIT;
in_pixel.have_tRNS = have_tRNS;
/* For error detection, below. */
r = in_pixel.red;
g = in_pixel.green;
b = in_pixel.blue;
a = in_pixel.alpha;
dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
/* Read the output pixel and compare it to what we got, we don't
* use the error field here, so no need to update sBIT.
*/
image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette);
/* We don't expect changes to the index here even if the bit depth is
* changed.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE &&
out_ct == PNG_COLOR_TYPE_PALETTE)
{
if (in_pixel.palette_index != out_pixel.palette_index)
png_error(pp, "unexpected transformed palette index");
}
/* Check the colours for palette images too - in fact the palette could
* be separately verified itself in most cases.
*/
if (in_pixel.red != out_pixel.red)
transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
out_pixel.red, sample_depth, in_pixel.rede,
dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.green != out_pixel.green)
transform_range_check(pp, r, g, b, a, in_pixel.green,
in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.blue != out_pixel.blue)
transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
out_pixel.blue, sample_depth, in_pixel.bluee,
dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
in_pixel.alpha != out_pixel.alpha)
transform_range_check(pp, r, g, b, a, in_pixel.alpha,
in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
digitization_error);
} /* pixel (x) loop */
} /* row (y) loop */
/* Record that something was actually checked to avoid a false positive. */
dp->this.ps->validated = 1;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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 check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
{
return m_annotatedRegions;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void agent_cancel_query(agent_pending_query *q)
{
assert(0 && "Windows agent queries are never asynchronous!");
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int ovl_want_write(struct dentry *dentry)
{
struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
return mnt_want_write(ofs->upper_mnt);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 write_to_fifo(AVFifoBuffer *fifo, AVFrame *buf)
{
int ret;
if (!av_fifo_space(fifo) &&
(ret = av_fifo_realloc2(fifo, 2*av_fifo_size(fifo)))) {
av_frame_free(&buf);
return ret;
}
av_fifo_generic_write(fifo, &buf, sizeof(buf), NULL);
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Extension::HasAPIPermission(const std::string& function_name) const {
base::AutoLock auto_lock(runtime_data_lock_);
return runtime_data_.GetActivePermissions()->
HasAccessToFunction(function_name);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
xmlInputCloseCallback ioclose, void *ioctx,
const char *URL,
const char *encoding, int options)
{
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (ioread == NULL)
return (NULL);
if (ctxt == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx,
XML_CHAR_ENCODING_NONE);
if (input == NULL) {
if (ioclose != NULL)
ioclose(ioctx);
return (NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 1));
}
CWE ID: CWE-611
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __dn_setsockopt(struct socket *sock, int level,int optname, char __user *optval, unsigned int optlen, int flags)
{
struct sock *sk = sock->sk;
struct dn_scp *scp = DN_SK(sk);
long timeo;
union {
struct optdata_dn opt;
struct accessdata_dn acc;
int mode;
unsigned long win;
int val;
unsigned char services;
unsigned char info;
} u;
int err;
if (optlen && !optval)
return -EINVAL;
if (optlen > sizeof(u))
return -EINVAL;
if (copy_from_user(&u, optval, optlen))
return -EFAULT;
switch (optname) {
case DSO_CONDATA:
if (sock->state == SS_CONNECTED)
return -EISCONN;
if ((scp->state != DN_O) && (scp->state != DN_CR))
return -EINVAL;
if (optlen != sizeof(struct optdata_dn))
return -EINVAL;
if (le16_to_cpu(u.opt.opt_optl) > 16)
return -EINVAL;
memcpy(&scp->conndata_out, &u.opt, optlen);
break;
case DSO_DISDATA:
if (sock->state != SS_CONNECTED &&
scp->accept_mode == ACC_IMMED)
return -ENOTCONN;
if (optlen != sizeof(struct optdata_dn))
return -EINVAL;
if (le16_to_cpu(u.opt.opt_optl) > 16)
return -EINVAL;
memcpy(&scp->discdata_out, &u.opt, optlen);
break;
case DSO_CONACCESS:
if (sock->state == SS_CONNECTED)
return -EISCONN;
if (scp->state != DN_O)
return -EINVAL;
if (optlen != sizeof(struct accessdata_dn))
return -EINVAL;
if ((u.acc.acc_accl > DN_MAXACCL) ||
(u.acc.acc_passl > DN_MAXACCL) ||
(u.acc.acc_userl > DN_MAXACCL))
return -EINVAL;
memcpy(&scp->accessdata, &u.acc, optlen);
break;
case DSO_ACCEPTMODE:
if (sock->state == SS_CONNECTED)
return -EISCONN;
if (scp->state != DN_O)
return -EINVAL;
if (optlen != sizeof(int))
return -EINVAL;
if ((u.mode != ACC_IMMED) && (u.mode != ACC_DEFER))
return -EINVAL;
scp->accept_mode = (unsigned char)u.mode;
break;
case DSO_CONACCEPT:
if (scp->state != DN_CR)
return -EINVAL;
timeo = sock_rcvtimeo(sk, 0);
err = dn_confirm_accept(sk, &timeo, sk->sk_allocation);
return err;
case DSO_CONREJECT:
if (scp->state != DN_CR)
return -EINVAL;
scp->state = DN_DR;
sk->sk_shutdown = SHUTDOWN_MASK;
dn_nsp_send_disc(sk, 0x38, 0, sk->sk_allocation);
break;
default:
#ifdef CONFIG_NETFILTER
return nf_setsockopt(sk, PF_DECnet, optname, optval, optlen);
#endif
case DSO_LINKINFO:
case DSO_STREAM:
case DSO_SEQPACKET:
return -ENOPROTOOPT;
case DSO_MAXWINDOW:
if (optlen != sizeof(unsigned long))
return -EINVAL;
if (u.win > NSP_MAX_WINDOW)
u.win = NSP_MAX_WINDOW;
if (u.win == 0)
return -EINVAL;
scp->max_window = u.win;
if (scp->snd_window > u.win)
scp->snd_window = u.win;
break;
case DSO_NODELAY:
if (optlen != sizeof(int))
return -EINVAL;
if (scp->nonagle == 2)
return -EINVAL;
scp->nonagle = (u.val == 0) ? 0 : 1;
/* if (scp->nonagle == 1) { Push pending frames } */
break;
case DSO_CORK:
if (optlen != sizeof(int))
return -EINVAL;
if (scp->nonagle == 1)
return -EINVAL;
scp->nonagle = (u.val == 0) ? 0 : 2;
/* if (scp->nonagle == 0) { Push pending frames } */
break;
case DSO_SERVICES:
if (optlen != sizeof(unsigned char))
return -EINVAL;
if ((u.services & ~NSP_FC_MASK) != 0x01)
return -EINVAL;
if ((u.services & NSP_FC_MASK) == NSP_FC_MASK)
return -EINVAL;
scp->services_loc = u.services;
break;
case DSO_INFO:
if (optlen != sizeof(unsigned char))
return -EINVAL;
if (u.info & 0xfc)
return -EINVAL;
scp->info_loc = u.info;
break;
}
return 0;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IceGenerateMagicCookie (
int len
)
{
char *auth;
#ifndef HAVE_ARC4RANDOM_BUF
long ldata[2];
int seed;
int value;
int i;
#endif
if ((auth = malloc (len + 1)) == NULL)
return (NULL);
#ifdef HAVE_ARC4RANDOM_BUF
arc4random_buf(auth, len);
#else
#ifdef ITIMER_REAL
{
struct timeval now;
int i;
ldata[0] = now.tv_sec;
ldata[1] = now.tv_usec;
}
#else
{
long time ();
ldata[0] = time ((long *) 0);
ldata[1] = getpid ();
}
#endif
seed = (ldata[0]) + (ldata[1] << 16);
srand (seed);
for (i = 0; i < len; i++)
ldata[1] = now.tv_usec;
value = rand ();
auth[i] = value & 0xff;
}
CWE ID: CWE-331
Target: 1
Example 2:
Code: void AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) {
if (queued_updates_.find(observer) != queued_updates_.end())
queued_observers_.AddObserver(observer);
else
observers_.AddObserver(observer);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RuntimeEnabledVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
impl->runtimeEnabledVoidMethod();
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
int bit_depth, unsigned int npalette, int interlace_type,
png_uint_32 w, png_uint_32 h, int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
if (npalette > 0)
{
pos = safecat(buffer, bufsize, pos, "[");
pos = safecatn(buffer, bufsize, pos, npalette);
pos = safecat(buffer, bufsize, pos, "]");
}
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, bit_depth);
pos = safecat(buffer, bufsize, pos, " bit");
if (interlace_type != PNG_INTERLACE_NONE)
{
pos = safecat(buffer, bufsize, pos, " interlaced");
if (do_interlace)
pos = safecat(buffer, bufsize, pos, "(pngvalid)");
else
pos = safecat(buffer, bufsize, pos, "(libpng)");
}
if (w > 0 || h > 0)
{
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, w);
pos = safecat(buffer, bufsize, pos, "x");
pos = safecatn(buffer, bufsize, pos, h);
}
return pos;
}
CWE ID:
Target: 1
Example 2:
Code: static long restore_sigcontext(struct pt_regs *regs, sigset_t *set, int sig,
struct sigcontext __user *sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs;
#endif
unsigned long err = 0;
unsigned long save_r13 = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* If this is not a signal return, we preserve the TLS in r13 */
if (!sig)
save_r13 = regs->gpr[13];
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, sc->gp_regs, sizeof(regs->gpr));
err |= __get_user(regs->nip, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
if (sig)
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
err |= __get_user(regs->orig_gpr3, &sc->gp_regs[PT_ORIG_R3]);
err |= __get_user(regs->ctr, &sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &sc->gp_regs[PT_CCR]);
/* skip SOFTE */
regs->trap = 0;
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
if (!sig)
regs->gpr[13] = save_r13;
if (set != NULL)
err |= __get_user(set->sig[0], &sc->oldmask);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && (msr & MSR_VEC) != 0)
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
else if (current->thread.used_vr)
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
/* Always get VRSAVE back */
if (v_regs != NULL)
err |= __get_user(current->thread.vrsave, (u32 __user *)&v_regs[33]);
else
current->thread.vrsave = 0;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
v_regs += ELF_NVRREG;
if ((msr & MSR_VSX) != 0)
err |= copy_vsx_from_user(current, v_regs);
else
for (i = 0; i < 32 ; i++)
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
#endif
return err;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 swizzleImageData(unsigned char* srcAddr,
size_t height,
size_t bytesPerRow,
bool flipY) {
if (flipY) {
for (size_t i = 0; i < height / 2; i++) {
size_t topRowStartPosition = i * bytesPerRow;
size_t bottomRowStartPosition = (height - 1 - i) * bytesPerRow;
if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle
for (size_t j = 0; j < bytesPerRow; j += 4) {
std::swap(srcAddr[topRowStartPosition + j],
srcAddr[bottomRowStartPosition + j + 2]);
std::swap(srcAddr[topRowStartPosition + j + 1],
srcAddr[bottomRowStartPosition + j + 1]);
std::swap(srcAddr[topRowStartPosition + j + 2],
srcAddr[bottomRowStartPosition + j]);
std::swap(srcAddr[topRowStartPosition + j + 3],
srcAddr[bottomRowStartPosition + j + 3]);
}
} else {
std::swap_ranges(srcAddr + topRowStartPosition,
srcAddr + topRowStartPosition + bytesPerRow,
srcAddr + bottomRowStartPosition);
}
}
} else {
if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle
for (size_t i = 0; i < height * bytesPerRow; i += 4)
std::swap(srcAddr[i], srcAddr[i + 2]);
}
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef");
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: gc_generational_mode_set(mrb_state *mrb, mrb_value self)
{
mrb_bool enable;
mrb_get_args(mrb, "b", &enable);
if (mrb->gc.generational != enable)
change_gen_gc_mode(mrb, &mrb->gc, enable);
return mrb_bool_value(enable);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 IndexPacket *GetAuthenticIndexesFromCache(const Image *image)
{
CacheInfo
*restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->indexes);
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UpdateContentLengthPrefs(int received_content_length,
int original_content_length,
bool via_data_reduction_proxy) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK_GE(received_content_length, 0);
DCHECK_GE(original_content_length, 0);
if (!g_browser_process)
return;
PrefService* prefs = g_browser_process->local_state();
if (!prefs)
return;
#if defined(OS_ANDROID)
bool with_data_reduction_proxy_enabled =
g_browser_process->profile_manager()->GetDefaultProfile()->
GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled);
#else
bool with_data_reduction_proxy_enabled = false;
#endif
chrome_browser_net::UpdateContentLengthPrefs(
received_content_length,
original_content_length,
with_data_reduction_proxy_enabled,
via_data_reduction_proxy, prefs);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: CStarter::publishUpdateAd( ClassAd* ad )
{
return publishJobInfoAd(&m_job_list, ad);
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 shrink_dcache_sb(struct super_block *sb)
{
long freed;
do {
LIST_HEAD(dispose);
freed = list_lru_walk(&sb->s_dentry_lru,
dentry_lru_isolate_shrink, &dispose, UINT_MAX);
this_cpu_sub(nr_dentry_unused, freed);
shrink_dentry_list(&dispose);
} while (freed > 0);
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: tt_cmap14_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_selectors;
if ( table + 2 + 4 + 4 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 2;
length = TT_NEXT_ULONG( p );
num_selectors = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
/* length < 10 + 11 * num_selectors ? */
length < 10 ||
( length - 10 ) / 11 < num_selectors )
FT_INVALID_TOO_SHORT;
/* check selectors, they must be in increasing order */
{
/* we start lastVarSel at 1 because a variant selector value of 0
* isn't valid.
*/
FT_ULong n, lastVarSel = 1;
for ( n = 0; n < num_selectors; n++ )
{
FT_ULong varSel = TT_NEXT_UINT24( p );
FT_ULong defOff = TT_NEXT_ULONG( p );
FT_ULong nondefOff = TT_NEXT_ULONG( p );
if ( defOff >= length || nondefOff >= length )
FT_INVALID_TOO_SHORT;
if ( varSel < lastVarSel )
FT_INVALID_DATA;
lastVarSel = varSel + 1;
/* check the default table (these glyphs should be reached */
/* through the normal Unicode cmap, no GIDs, just check order) */
if ( defOff != 0 )
{
FT_Byte* defp = table + defOff;
FT_ULong numRanges = TT_NEXT_ULONG( defp );
FT_ULong i;
FT_ULong lastBase = 0;
/* defp + numRanges * 4 > valid->limit ? */
if ( numRanges > (FT_ULong)( valid->limit - defp ) / 4 )
FT_INVALID_TOO_SHORT;
if ( base + cnt >= 0x110000UL ) /* end of Unicode */
FT_INVALID_DATA;
if ( base < lastBase )
FT_INVALID_DATA;
lastBase = base + cnt + 1U;
}
}
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings = TT_NEXT_ULONG( ndp );
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings = TT_NEXT_ULONG( ndp );
FT_ULong i, lastUni = 0;
/* numMappings * 4 > (FT_ULong)( valid->limit - ndp ) ? */
if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) / 4 )
FT_INVALID_TOO_SHORT;
for ( i = 0; i < numMappings; ++i )
lastUni = uni + 1U;
if ( valid->level >= FT_VALIDATE_TIGHT &&
gid >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void cm_mask_copy(u8 *dst, u8 *src, u8 *mask)
{
int i;
for (i = 0; i < IB_CM_COMPARE_SIZE / sizeof(unsigned long); i++)
((unsigned long *) dst)[i] = ((unsigned long *) src)[i] &
((unsigned long *) mask)[i];
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: size_t mptsas_config_ioc_1(MPTSASState *s, uint8_t **data, int address)
{
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_IOC, 0x03,
"*l*l*b*b*b*b");
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool WebviewInfo::IsResourceWebviewAccessible(
const Extension* extension,
const std::string& partition_id,
const std::string& relative_path) {
if (!extension)
return false;
const WebviewInfo* info = GetResourcesInfo(*extension);
if (!info)
return false;
bool partition_is_privileged = false;
for (size_t i = 0;
i < info->webview_privileged_partitions_.size();
++i) {
if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) {
partition_is_privileged = true;
break;
}
}
return partition_is_privileged && extension->ResourceMatches(
info->webview_accessible_resources_, relative_path);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void rpc_delay(struct rpc_task *task, unsigned long delay)
{
task->tk_timeout = delay;
rpc_sleep_on(&delay_queue, task, __rpc_atrun);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: lrmd_remote_client_msg(gpointer data)
{
int id = 0;
int rc = 0;
int disconnected = 0;
xmlNode *request = NULL;
crm_client_t *client = data;
if (client->remote->tls_handshake_complete == FALSE) {
int rc = 0;
/* Muliple calls to handshake will be required, this callback
* will be invoked once the client sends more handshake data. */
do {
rc = gnutls_handshake(*client->remote->tls_session);
if (rc < 0 && rc != GNUTLS_E_AGAIN) {
crm_err("Remote lrmd tls handshake failed");
return -1;
}
} while (rc == GNUTLS_E_INTERRUPTED);
if (rc == 0) {
crm_debug("Remote lrmd tls handshake completed");
client->remote->tls_handshake_complete = TRUE;
if (client->remote->auth_timeout) {
g_source_remove(client->remote->auth_timeout);
}
client->remote->auth_timeout = 0;
}
return 0;
}
rc = crm_remote_ready(client->remote, 0);
if (rc == 0) {
/* no msg to read */
return 0;
} else if (rc < 0) {
crm_info("Client disconnected during remote client read");
return -1;
}
crm_remote_recv(client->remote, -1, &disconnected);
request = crm_remote_parse_buffer(client->remote);
while (request) {
crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id);
crm_trace("processing request from remote client with remote msg id %d", id);
if (!client->name) {
const char *value = crm_element_value(request, F_LRMD_CLIENTNAME);
if (value) {
client->name = strdup(value);
}
}
lrmd_call_id++;
if (lrmd_call_id < 1) {
lrmd_call_id = 1;
}
crm_xml_add(request, F_LRMD_CLIENTID, client->id);
crm_xml_add(request, F_LRMD_CLIENTNAME, client->name);
crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id);
process_lrmd_message(client, id, request);
free_xml(request);
/* process all the messages in the current buffer */
request = crm_remote_parse_buffer(client->remote);
}
if (disconnected) {
crm_info("Client disconnect detected in tls msg dispatcher.");
return -1;
}
return 0;
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
if (getGraphicBufferSource() != NULL) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2;
int thick = im->thick;
int t;
if (x1 == x2 && y1 == y2 && thick == 1) {
gdImageSetPixel(im, x1, y1, color);
return;
}
if (y2 < y1) {
t=y1;
y1 = y2;
y2 = t;
}
if (x2 < x1) {
t = x1;
x1 = x2;
x2 = t;
}
x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2;
if (thick > 1) {
int cx, cy, x1ul, y1ul, x2lr, y2lr;
int half = thick >> 1;
x1ul = x1 - half;
y1ul = y1 - half;
x2lr = x2 + half;
y2lr = y2 + half;
cy = y1ul + thick;
while (cy-- > y1ul) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y2lr - thick;
while (cy++ < y2lr) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x1ul - 1;
while (cx++ < x1ul + thick) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x2lr - thick - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
return;
} else {
if (x1 == x2 || y1 == y2) {
gdImageLine(im, x1, y1, x2, y2, color);
} else {
y1v = y1h + 1;
y2v = y2h - 1;
gdImageLine(im, x1h, y1h, x2h, y1h, color);
gdImageLine(im, x1h, y2h, x2h, y2h, color);
gdImageLine(im, x1v, y1v, x1v, y2v, color);
gdImageLine(im, x2v, y1v, x2v, y2v, color);
}
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf)
{
git_pkt *pkt;
const char *line, *line_end = NULL;
size_t line_len;
int error;
int reading_from_buf = data_pkt_buf->size > 0;
if (reading_from_buf) {
/* We had an existing partial packet, so add the new
* packet to the buffer and parse the whole thing */
git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len);
line = data_pkt_buf->ptr;
line_len = data_pkt_buf->size;
}
else {
line = data_pkt->data;
line_len = data_pkt->len;
}
while (line_len > 0) {
error = git_pkt_parse_line(&pkt, line, &line_end, line_len);
if (error == GIT_EBUFS) {
/* Buffer the data when the inner packet is split
* across multiple sideband packets */
if (!reading_from_buf)
git_buf_put(data_pkt_buf, line, line_len);
error = 0;
goto done;
}
else if (error < 0)
goto done;
/* Advance in the buffer */
line_len -= (line_end - line);
line = line_end;
/* When a valid packet with no content has been
* read, git_pkt_parse_line does not report an
* error, but the pkt pointer has not been set.
* Handle this by skipping over empty packets.
*/
if (pkt == NULL)
continue;
error = add_push_report_pkt(push, pkt);
git_pkt_free(pkt);
if (error < 0 && error != GIT_ITEROVER)
goto done;
}
error = 0;
done:
if (reading_from_buf)
git_buf_consume(data_pkt_buf, line_end);
return error;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void SafeBrowsingBlockingPage::OnDontProceed() {
RecordUserReactionTime(kNavigatedAwayMetaCommand);
if (proceeded_)
return;
RecordUserAction(DONT_PROCEED);
FinishMalwareDetails(0); // No delay
NotifySafeBrowsingUIManager(ui_manager_, unsafe_resources_, false);
UnsafeResourceMap* unsafe_resource_map = GetUnsafeResourcesMap();
UnsafeResourceMap::iterator iter = unsafe_resource_map->find(web_contents_);
if (iter != unsafe_resource_map->end() && !iter->second.empty()) {
NotifySafeBrowsingUIManager(ui_manager_, iter->second, false);
unsafe_resource_map->erase(iter);
}
int last_committed_index =
web_contents_->GetController().GetLastCommittedEntryIndex();
if (navigation_entry_index_to_remove_ != -1 &&
navigation_entry_index_to_remove_ != last_committed_index &&
!web_contents_->IsBeingDestroyed()) {
web_contents_->GetController().RemoveEntryAtIndex(
navigation_entry_index_to_remove_);
navigation_entry_index_to_remove_ = -1;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 vfat_revalidate_shortname(struct dentry *dentry)
{
int ret = 1;
spin_lock(&dentry->d_lock);
if (dentry->d_time != dentry->d_parent->d_inode->i_version)
ret = 0;
spin_unlock(&dentry->d_lock);
return ret;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int setup_dev_console(const struct lxc_rootfs *rootfs,
const struct lxc_console *console)
{
char path[MAXPATHLEN];
struct stat s;
int ret;
ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount);
if (ret >= sizeof(path)) {
ERROR("console path too long");
return -1;
}
if (access(path, F_OK)) {
WARN("rootfs specified but no console found at '%s'", path);
return 0;
}
if (console->master < 0) {
INFO("no console");
return 0;
}
if (stat(path, &s)) {
SYSERROR("failed to stat '%s'", path);
return -1;
}
if (chmod(console->name, s.st_mode)) {
SYSERROR("failed to set mode '0%o' to '%s'",
s.st_mode, console->name);
return -1;
}
if (mount(console->name, path, "none", MS_BIND, 0)) {
ERROR("failed to mount '%s' on '%s'", console->name, path);
return -1;
}
INFO("console has been setup");
return 0;
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: ZEND_API void ZEND_FASTCALL zend_hash_internal_pointer_reset_ex(HashTable *ht, HashPosition *pos)
{
uint32_t idx;
IS_CONSISTENT(ht);
HT_ASSERT(&ht->nInternalPointer != pos || GC_REFCOUNT(ht) == 1);
for (idx = 0; idx < ht->nNumUsed; idx++) {
if (Z_TYPE(ht->arData[idx].val) != IS_UNDEF) {
*pos = idx;
return;
}
}
*pos = HT_INVALID_IDX;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 struct msg_queue *msg_lock_check(struct ipc_namespace *ns,
int id)
{
struct kern_ipc_perm *ipcp = ipc_lock_check(&msg_ids(ns), id);
if (IS_ERR(ipcp))
return (struct msg_queue *)ipcp;
return container_of(ipcp, struct msg_queue, q_perm);
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element* element, Namespaces* namespaces)
{
if (element->hasTagName(HTMLNames::baseTag)) {
result.append("<!--");
} else if (element->hasTagName(HTMLNames::htmlTag)) {
result.append(String::format("\n<!-- saved from url=(%04d)%s -->\n",
static_cast<int>(m_document->url().string().utf8().length()),
m_document->url().string().utf8().data()));
}
SerializerMarkupAccumulator::appendElement(result, element, namespaces);
if (element->hasTagName(HTMLNames::baseTag)) {
result.appendLiteral("-->");
result.appendLiteral("<base href=\".\"");
if (!m_document->baseTarget().isEmpty()) {
result.appendLiteral(" target=\"");
result.append(m_document->baseTarget());
result.append('"');
}
if (m_document->isXHTMLDocument())
result.appendLiteral(" />");
else
result.appendLiteral(">");
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool btif_av_is_sink_enabled(void) {
return (bt_av_sink_callbacks != NULL) ? true : false;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int phar_call_openssl_signverify(int is_sign, php_stream *fp, zend_off_t end, char *key, int key_len, char **signature, int *signature_len) /* {{{ */
{
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval retval, zp[3], openssl;
zend_string *str;
ZVAL_STRINGL(&openssl, is_sign ? "openssl_sign" : "openssl_verify", is_sign ? sizeof("openssl_sign")-1 : sizeof("openssl_verify")-1);
ZVAL_STRINGL(&zp[1], *signature, *signature_len);
ZVAL_STRINGL(&zp[2], key, key_len);
php_stream_rewind(fp);
str = php_stream_copy_to_mem(fp, (size_t) end, 0);
if (str) {
ZVAL_STR(&zp[0], str);
} else {
ZVAL_EMPTY_STRING(&zp[0]);
}
if (end != Z_STRLEN(zp[0])) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
if (FAILURE == zend_fcall_info_init(&openssl, 0, &fci, &fcc, NULL, NULL)) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
fci.param_count = 3;
fci.params = zp;
Z_ADDREF(zp[0]);
if (is_sign) {
ZVAL_NEW_REF(&zp[1], &zp[1]);
} else {
Z_ADDREF(zp[1]);
}
Z_ADDREF(zp[2]);
fci.retval = &retval;
if (FAILURE == zend_call_function(&fci, &fcc)) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
zval_dtor(&openssl);
Z_DELREF(zp[0]);
if (is_sign) {
ZVAL_UNREF(&zp[1]);
} else {
Z_DELREF(zp[1]);
}
Z_DELREF(zp[2]);
zval_dtor(&zp[0]);
zval_dtor(&zp[2]);
switch (Z_TYPE(retval)) {
default:
case IS_LONG:
zval_dtor(&zp[1]);
if (1 == Z_LVAL(retval)) {
return SUCCESS;
}
return FAILURE;
case IS_TRUE:
*signature = estrndup(Z_STRVAL(zp[1]), Z_STRLEN(zp[1]));
*signature_len = Z_STRLEN(zp[1]);
zval_dtor(&zp[1]);
return SUCCESS;
case IS_FALSE:
zval_dtor(&zp[1]);
return FAILURE;
}
}
/* }}} */
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
horDiff16(tif, cp0, cc);
TIFFSwabArrayOfShort(wp, wc);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AutofillPopupItemView::OnMouseEntered(const ui::MouseEvent& event) {
AutofillPopupController* controller = popup_view_->controller();
if (controller)
controller->SetSelectedLine(line_number_);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getShaderParameterCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getShaderParameter()");
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLShader::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
WebGLShader* shader = V8WebGLShader::HasInstance(args[0]) ? V8WebGLShader::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0;
unsigned pname = toInt32(args[1]);
WebGLGetInfo info = context->getShaderParameter(shader, pname, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NavigationControllerImpl::RendererDidNavigateToExistingPage(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
bool is_in_page,
bool was_restored,
NavigationHandleImpl* handle) {
DCHECK(!rfh->GetParent());
NavigationEntryImpl* entry;
if (params.intended_as_new_entry) {
entry = GetLastCommittedEntry();
} else if (params.nav_entry_id) {
entry = GetEntryWithUniqueID(params.nav_entry_id);
if (is_in_page) {
NavigationEntryImpl* last_entry = GetLastCommittedEntry();
if (entry->GetURL().GetOrigin() == last_entry->GetURL().GetOrigin() &&
last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
was_restored) {
entry->GetSSL() = last_entry->GetSSL();
}
} else {
entry->GetSSL() = handle->ssl_status();
}
} else {
entry = GetLastCommittedEntry();
if (!is_in_page)
entry->GetSSL() = handle->ssl_status();
}
DCHECK(entry);
entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
: PAGE_TYPE_NORMAL);
entry->SetURL(params.url);
entry->SetReferrer(params.referrer);
if (entry->update_virtual_url_with_url())
UpdateVirtualURLToURL(entry, params.url);
DCHECK(entry->site_instance() == nullptr ||
!entry->GetRedirectChain().empty() ||
entry->site_instance() == rfh->GetSiteInstance());
entry->AddOrUpdateFrameEntry(
rfh->frame_tree_node(), params.item_sequence_number,
params.document_sequence_number, rfh->GetSiteInstance(), nullptr,
params.url, params.referrer, params.redirects, params.page_state,
params.method, params.post_id);
if (ui::PageTransitionIsRedirect(params.transition) && !is_in_page)
entry->GetFavicon() = FaviconStatus();
DiscardNonCommittedEntriesInternal();
last_committed_entry_index_ = GetIndexOfEntry(entry);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: add_policy_mods(krb5_context context, LDAPMod ***mods, osa_policy_ent_t policy,
int op)
{
krb5_error_code st;
char *strval[2] = { NULL };
st = krb5_add_int_mem_ldap_mod(mods, "krbmaxpwdlife", op,
(int)policy->pw_max_life);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbminpwdlife", op,
(int)policy->pw_min_life);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdmindiffchars", op,
(int)policy->pw_min_classes);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdminlength", op,
(int)policy->pw_min_length);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdhistorylength", op,
(int)policy->pw_history_num);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdmaxfailure", op,
(int)policy->pw_max_fail);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdfailurecountinterval", op,
(int)policy->pw_failcnt_interval);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdlockoutduration", op,
(int)policy->pw_lockout_duration);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdattributes", op,
(int)policy->attributes);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdmaxlife", op,
(int)policy->max_life);
if (st)
return st;
st = krb5_add_int_mem_ldap_mod(mods, "krbpwdmaxrenewablelife", op,
(int)policy->max_renewable_life);
if (st)
return st;
if (policy->allowed_keysalts != NULL) {
strval[0] = policy->allowed_keysalts;
st = krb5_add_str_mem_ldap_mod(mods, "krbpwdallowedkeysalts",
op, strval);
if (st)
return st;
}
/*
* Each policy tl-data type we add should be explicitly marshalled here.
* Unlike principals, we do not marshal unrecognized policy tl-data.
*/
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 ReflectItemStatus(const ash::LauncherItem& item,
LauncherButton* button) {
switch (item.status) {
case STATUS_CLOSED:
button->ClearState(LauncherButton::STATE_ACTIVE);
button->ClearState(LauncherButton::STATE_RUNNING);
button->ClearState(LauncherButton::STATE_ATTENTION);
button->ClearState(LauncherButton::STATE_PENDING);
break;
case STATUS_RUNNING:
button->ClearState(LauncherButton::STATE_ACTIVE);
button->AddState(LauncherButton::STATE_RUNNING);
button->ClearState(LauncherButton::STATE_ATTENTION);
button->ClearState(LauncherButton::STATE_PENDING);
break;
case STATUS_ACTIVE:
button->AddState(LauncherButton::STATE_ACTIVE);
button->ClearState(LauncherButton::STATE_RUNNING);
button->ClearState(LauncherButton::STATE_ATTENTION);
button->ClearState(LauncherButton::STATE_PENDING);
break;
case STATUS_ATTENTION:
button->ClearState(LauncherButton::STATE_ACTIVE);
button->ClearState(LauncherButton::STATE_RUNNING);
button->AddState(LauncherButton::STATE_ATTENTION);
button->ClearState(LauncherButton::STATE_PENDING);
break;
case STATUS_IS_PENDING:
button->ClearState(LauncherButton::STATE_ACTIVE);
button->ClearState(LauncherButton::STATE_RUNNING);
button->ClearState(LauncherButton::STATE_ATTENTION);
button->AddState(LauncherButton::STATE_PENDING);
break;
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void QuicClientPromisedInfo::Init() {
cleanup_alarm_.reset(session_->connection()->alarm_factory()->CreateAlarm(
new QuicClientPromisedInfo::CleanupAlarm(this)));
cleanup_alarm_->Set(
session_->connection()->helper()->GetClock()->ApproximateNow() +
QuicTime::Delta::FromSeconds(kPushPromiseTimeoutSecs));
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 btrfs_flush_all_pending_stuffs(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int flush_on_commit = btrfs_test_opt(root, FLUSHONCOMMIT);
int snap_pending = 0;
int ret;
if (!flush_on_commit) {
spin_lock(&root->fs_info->trans_lock);
if (!list_empty(&trans->transaction->pending_snapshots))
snap_pending = 1;
spin_unlock(&root->fs_info->trans_lock);
}
if (flush_on_commit || snap_pending) {
btrfs_start_delalloc_inodes(root, 1);
btrfs_wait_ordered_extents(root, 1);
}
ret = btrfs_run_delayed_items(trans, root);
if (ret)
return ret;
/*
* running the delayed items may have added new refs. account
* them now so that they hinder processing of more delayed refs
* as little as possible.
*/
btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
/*
* rename don't use btrfs_join_transaction, so, once we
* set the transaction to blocked above, we aren't going
* to get any new ordered operations. We can safely run
* it here and no for sure that nothing new will be added
* to the list
*/
btrfs_run_ordered_operations(root, 1);
return 0;
}
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
_cleanup_close_ int fd;
int r;
assert(path);
if (parents)
mkdir_parents(path, 0755);
fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
if (fd < 0)
return -errno;
if (mode > 0) {
r = fchmod(fd, mode);
if (r < 0)
return -errno;
}
if (uid != UID_INVALID || gid != GID_INVALID) {
r = fchown(fd, uid, gid);
if (r < 0)
return -errno;
}
if (stamp != USEC_INFINITY) {
struct timespec ts[2];
timespec_store(&ts[0], stamp);
ts[1] = ts[0];
r = futimens(fd, ts);
} else
r = futimens(fd, NULL);
if (r < 0)
return -errno;
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static inline void cap_emulate_setxuid(struct cred *new, const struct cred *old)
{
if ((old->uid == 0 || old->euid == 0 || old->suid == 0) &&
(new->uid != 0 && new->euid != 0 && new->suid != 0) &&
!issecure(SECURE_KEEP_CAPS)) {
cap_clear(new->cap_permitted);
cap_clear(new->cap_effective);
}
if (old->euid == 0 && new->euid != 0)
cap_clear(new->cap_effective);
if (old->euid != 0 && new->euid == 0)
new->cap_effective = new->cap_permitted;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() {
return this;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int i, pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
dev_dbg(dev, "Checking memory size\n");
i = 0x12345678;
catc_write_mem(catc, 0x7a80, &i, 4);
i = 0x87654321;
catc_write_mem(catc, 0xfa80, &i, 4);
catc_read_mem(catc, 0x7a80, &i, 4);
switch (i) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static const char *register_named_block_function_hook(const char *name,
cmd_parms *cmd,
void *mconfig,
const char *line)
{
const char *function = NULL;
ap_lua_mapped_handler_spec *spec;
int when = APR_HOOK_MIDDLE;
const char *endp = ap_strrchr_c(line, '>');
if (endp == NULL) {
return apr_pstrcat(cmd->pool, cmd->cmd->name,
"> directive missing closing '>'", NULL);
}
line = apr_pstrndup(cmd->temp_pool, line, endp - line);
if (line[0]) {
const char *word;
word = ap_getword_conf(cmd->temp_pool, &line);
if (*word) {
function = apr_pstrdup(cmd->pool, word);
}
word = ap_getword_conf(cmd->temp_pool, &line);
if (*word) {
if (!strcasecmp("early", word)) {
when = AP_LUA_HOOK_FIRST;
}
else if (!strcasecmp("late", word)) {
when = AP_LUA_HOOK_LAST;
}
else {
return apr_pstrcat(cmd->pool, cmd->cmd->name,
"> 2nd argument must be 'early' or 'late'", NULL);
}
}
}
spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));
{
cr_ctx ctx;
lua_State *lvm;
char *tmp;
int rv;
ap_directive_t **current;
hack_section_baton *baton;
spec->file_name = apr_psprintf(cmd->pool, "%s:%u",
cmd->config_file->name,
cmd->config_file->line_number);
if (function) {
spec->function_name = (char *) function;
}
else {
function = NULL;
}
ctx.cmd = cmd;
tmp = apr_pstrdup(cmd->pool, cmd->err_directive->directive + 1);
ap_str_tolower(tmp);
ctx.endstr = tmp;
ctx.cfp = cmd->config_file;
ctx.startline = cmd->config_file->line_number;
/* This lua State is used only to compile the input strings -> bytecode, so we don't need anything extra. */
lvm = luaL_newstate();
lua_settop(lvm, 0);
rv = lua_load(lvm, direct_chunkreader, &ctx, spec->file_name);
if (rv != 0) {
const char *errstr = apr_pstrcat(cmd->pool, "Lua Error:",
lua_tostring(lvm, -1), NULL);
lua_close(lvm);
return errstr;
}
else {
luaL_Buffer b;
luaL_buffinit(lvm, &b);
lua_dump(lvm, ldump_writer, &b);
luaL_pushresult(&b);
spec->bytecode_len = lua_strlen(lvm, -1);
spec->bytecode = apr_pstrmemdup(cmd->pool, lua_tostring(lvm, -1),
spec->bytecode_len);
lua_close(lvm);
}
current = mconfig;
/* Here, we have to replace our current config node for the next pass */
if (!*current) {
*current = apr_pcalloc(cmd->pool, sizeof(**current));
}
baton = apr_pcalloc(cmd->pool, sizeof(hack_section_baton));
baton->name = name;
baton->spec = spec;
baton->apr_hook_when = when;
(*current)->filename = cmd->config_file->name;
(*current)->line_num = cmd->config_file->line_number;
(*current)->directive = apr_pstrdup(cmd->pool, "Lua_____ByteCodeHack");
(*current)->args = NULL;
(*current)->data = baton;
}
return NULL;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 prepare_binprm(struct linux_binprm *bprm)
{
struct inode *inode = file_inode(bprm->file);
umode_t mode = inode->i_mode;
int retval;
/* clear any previous set[ug]id data from a previous binary */
bprm->cred->euid = current_euid();
bprm->cred->egid = current_egid();
if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) &&
!task_no_new_privs(current) &&
kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) &&
kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) {
/* Set-uid? */
if (mode & S_ISUID) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->euid = inode->i_uid;
}
/* Set-gid? */
/*
* If setgid is set but no group execute bit then this
* is a candidate for mandatory locking, not a setgid
* executable.
*/
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
bprm->per_clear |= PER_CLEAR_ON_SETID;
bprm->cred->egid = inode->i_gid;
}
}
/* fill in binprm security blob */
retval = security_bprm_set_creds(bprm);
if (retval)
return retval;
bprm->cred_prepared = 1;
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper(
ppapi::host::ResourceHost* resource_host,
Delegate* delegate,
PP_DeviceType_Dev device_type,
const GURL& document_url)
: resource_host_(resource_host),
delegate_(delegate),
device_type_(device_type),
document_url_(document_url) {}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool ServiceWorkerDevToolsAgentHost::Close() {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&TerminateServiceWorkerOnIO, context_weak_, version_id_));
return true;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ExprCreateKeyName(xkb_atom_t key_name)
{
EXPR_CREATE(ExprKeyName, expr, EXPR_VALUE, EXPR_TYPE_KEYNAME);
expr->key_name.key_name = key_name;
return expr;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SortDirection AXTableCell::getSortDirection() const {
if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole)
return SortDirectionUndefined;
const AtomicString& ariaSort =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort);
if (ariaSort.isEmpty())
return SortDirectionUndefined;
if (equalIgnoringCase(ariaSort, "none"))
return SortDirectionNone;
if (equalIgnoringCase(ariaSort, "ascending"))
return SortDirectionAscending;
if (equalIgnoringCase(ariaSort, "descending"))
return SortDirectionDescending;
if (equalIgnoringCase(ariaSort, "other"))
return SortDirectionOther;
return SortDirectionUndefined;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static int make_proc_exitcode(void)
{
struct proc_dir_entry *ent;
ent = proc_create("exitcode", 0600, NULL, &exitcode_proc_fops);
if (ent == NULL) {
printk(KERN_WARNING "make_proc_exitcode : Failed to register "
"/proc/exitcode\n");
return 0;
}
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
CWE ID: CWE-94
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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[]) {
char *fin, *fout;
FILE *fpin, *fpout;
uint8_t *inbuf, *outbuf;
uint8_t *inbuf_u, *outbuf_u;
uint8_t *inbuf_v, *outbuf_v;
int f, frames;
int width, height, target_width, target_height;
if (argc < 5) {
printf("Incorrect parameters:\n");
usage(argv[0]);
return 1;
}
fin = argv[1];
fout = argv[4];
if (!parse_dim(argv[2], &width, &height)) {
printf("Incorrect parameters: %s\n", argv[2]);
usage(argv[0]);
return 1;
}
if (!parse_dim(argv[3], &target_width, &target_height)) {
printf("Incorrect parameters: %s\n", argv[3]);
usage(argv[0]);
return 1;
}
fpin = fopen(fin, "rb");
if (fpin == NULL) {
printf("Can't open file %s to read\n", fin);
usage(argv[0]);
return 1;
}
fpout = fopen(fout, "wb");
if (fpout == NULL) {
printf("Can't open file %s to write\n", fout);
usage(argv[0]);
return 1;
}
if (argc >= 6)
frames = atoi(argv[5]);
else
frames = INT_MAX;
printf("Input size: %dx%d\n",
width, height);
printf("Target size: %dx%d, Frames: ",
target_width, target_height);
if (frames == INT_MAX)
printf("All\n");
else
printf("%d\n", frames);
inbuf = (uint8_t*)malloc(width * height * 3 / 2);
outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2);
inbuf_u = inbuf + width * height;
inbuf_v = inbuf_u + width * height / 4;
outbuf_u = outbuf + target_width * target_height;
outbuf_v = outbuf_u + target_width * target_height / 4;
f = 0;
while (f < frames) {
if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1)
break;
vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2,
height, width,
outbuf, target_width, outbuf_u, outbuf_v,
target_width / 2,
target_height, target_width);
fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout);
f++;
}
printf("%d frames processed\n", f);
fclose(fpin);
fclose(fpout);
free(inbuf);
free(outbuf);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void sas_ata_task_abort(struct sas_task *task)
{
struct ata_queued_cmd *qc = task->uldd_task;
struct completion *waiting;
/* Bounce SCSI-initiated commands to the SCSI EH */
if (qc->scsicmd) {
struct request_queue *q = qc->scsicmd->device->request_queue;
unsigned long flags;
spin_lock_irqsave(q->queue_lock, flags);
blk_abort_request(qc->scsicmd->request);
spin_unlock_irqrestore(q->queue_lock, flags);
return;
}
/* Internal command, fake a timeout and complete. */
qc->flags &= ~ATA_QCFLAG_ACTIVE;
qc->flags |= ATA_QCFLAG_FAILED;
qc->err_mask |= AC_ERR_TIMEOUT;
waiting = qc->private_data;
complete(waiting);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: CacheAddr BackendImpl::GetNextAddr(Addr address) {
EntriesMap::iterator it = open_entries_.find(address.value());
if (it != open_entries_.end()) {
EntryImpl* this_entry = it->second;
return this_entry->GetNextAddress();
}
DCHECK(block_files_.IsValid(address));
DCHECK(!address.is_separate_file() && address.file_type() == BLOCK_256);
CacheEntryBlock entry(File(address), address);
CHECK(entry.Load());
return entry.Data()->next;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftHEVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
mReceivedEOS = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
setFlushMode();
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) {
ALOGE("Decoder arg setup failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
CWE ID: CWE-172
Target: 1
Example 2:
Code: bool get_resource_context_called() const {
return get_resource_context_called_;
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct object *get_reference(struct rev_info *revs, const char *name,
const unsigned char *sha1,
unsigned int flags)
{
struct object *object;
object = parse_object(sha1);
if (!object) {
if (revs->ignore_missing)
return object;
die("bad object %s", name);
}
object->flags |= flags;
return object;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
{
const bool shouldEmit = traversalMode == EmitString;
Vector<Node*> ancestorsToClose;
Node* next;
Node* lastClosed = 0;
for (Node* n = startNode; n != pastEnd; n = next) {
ASSERT(n);
if (!n)
break;
next = n->traverseNextNode();
bool openedTag = false;
if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
continue;
if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
next = n->traverseNextSibling();
if (pastEnd && pastEnd->isDescendantOf(n))
next = pastEnd;
} else {
if (shouldEmit)
appendStartTag(n);
if (!n->childNodeCount()) {
if (shouldEmit)
appendEndTag(n);
lastClosed = n;
} else {
openedTag = true;
ancestorsToClose.append(n);
}
}
if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
while (!ancestorsToClose.isEmpty()) {
Node* ancestor = ancestorsToClose.last();
if (next != pastEnd && next->isDescendantOf(ancestor))
break;
if (shouldEmit)
appendEndTag(ancestor);
lastClosed = ancestor;
ancestorsToClose.removeLast();
}
ContainerNode* nextParent = next ? next->parentNode() : 0;
if (next != pastEnd && n != nextParent) {
Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
if (!parent->renderer())
continue;
ASSERT(startNode->isDescendantOf(parent));
if (shouldEmit)
wrapWithNode(parent);
lastClosed = parent;
}
}
}
}
return lastClosed;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PromoResourceService::PromoResourceService(Profile* profile)
: WebResourceService(profile->GetPrefs(),
GetPromoResourceURL(),
true, // append locale to URL
prefs::kNtpPromoResourceCacheUpdate,
kStartResourceFetchDelay,
GetCacheUpdateDelay()),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(
weak_ptr_factory_(this)),
web_resource_update_scheduled_(false) {
ScheduleNotificationOnInit();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct pipe_inode_info *alloc_pipe_info(void)
{
struct pipe_inode_info *pipe;
pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL);
if (pipe) {
pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL);
if (pipe->bufs) {
init_waitqueue_head(&pipe->wait);
pipe->r_counter = pipe->w_counter = 1;
pipe->buffers = PIPE_DEF_BUFFERS;
mutex_init(&pipe->mutex);
return pipe;
}
kfree(pipe);
}
return NULL;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int hub_usb3_port_disable(struct usb_hub *hub, int port1)
{
int ret;
int total_time;
u16 portchange, portstatus;
if (!hub_is_superspeed(hub->hdev))
return -EINVAL;
ret = hub_port_status(hub, port1, &portstatus, &portchange);
if (ret < 0)
return ret;
/*
* USB controller Advanced Micro Devices, Inc. [AMD] FCH USB XHCI
* Controller [1022:7814] will have spurious result making the following
* usb 3.0 device hotplugging route to the 2.0 root hub and recognized
* as high-speed device if we set the usb 3.0 port link state to
* Disabled. Since it's already in USB_SS_PORT_LS_RX_DETECT state, we
* check the state here to avoid the bug.
*/
if ((portstatus & USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_RX_DETECT) {
dev_dbg(&hub->ports[port1 - 1]->dev,
"Not disabling port; link state is RxDetect\n");
return ret;
}
ret = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_SS_DISABLED);
if (ret)
return ret;
/* Wait for the link to enter the disabled state. */
for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
ret = hub_port_status(hub, port1, &portstatus, &portchange);
if (ret < 0)
return ret;
if ((portstatus & USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_SS_DISABLED)
break;
if (total_time >= HUB_DEBOUNCE_TIMEOUT)
break;
msleep(HUB_DEBOUNCE_STEP);
}
if (total_time >= HUB_DEBOUNCE_TIMEOUT)
dev_warn(&hub->ports[port1 - 1]->dev,
"Could not disable after %d ms\n", total_time);
return hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_RX_DETECT);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GLES2DecoderPassthroughImpl::GetFramebufferManager() {
return nullptr;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void alpha_perf_event_irq_handler(unsigned long la_ptr,
struct pt_regs *regs)
{
struct cpu_hw_events *cpuc;
struct perf_sample_data data;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, j;
__get_cpu_var(irq_pmi_count)++;
cpuc = &__get_cpu_var(cpu_hw_events);
/* Completely counting through the PMC's period to trigger a new PMC
* overflow interrupt while in this interrupt routine is utterly
* disastrous! The EV6 and EV67 counters are sufficiently large to
* prevent this but to be really sure disable the PMCs.
*/
wrperfmon(PERFMON_CMD_DISABLE, cpuc->idx_mask);
/* la_ptr is the counter that overflowed. */
if (unlikely(la_ptr >= alpha_pmu->num_pmcs)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: silly index %ld\n", la_ptr);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
idx = la_ptr;
perf_sample_data_init(&data, 0);
for (j = 0; j < cpuc->n_events; j++) {
if (cpuc->current_idx[j] == idx)
break;
}
if (unlikely(j == cpuc->n_events)) {
/* This can occur if the event is disabled right on a PMC overflow. */
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
event = cpuc->event[j];
if (unlikely(!event)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: No event at index %d!\n", idx);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
hwc = &event->hw;
alpha_perf_event_update(event, hwc, idx, alpha_pmu->pmc_max_period[idx]+1);
data.period = event->hw.last_period;
if (alpha_perf_event_set_period(event, hwc, idx)) {
if (perf_event_overflow(event, 1, &data, regs)) {
/* Interrupts coming too quickly; "throttle" the
* counter, i.e., disable it for a little while.
*/
alpha_pmu_stop(event, 0);
}
}
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void SkipInputData(j_decompress_ptr cinfo,long number_bytes)
{
SourceManager
*source;
if (number_bytes <= 0)
return;
source=(SourceManager *) cinfo->src;
while (number_bytes > (long) source->manager.bytes_in_buffer)
{
number_bytes-=(long) source->manager.bytes_in_buffer;
(void) FillInputBuffer(cinfo);
}
source->manager.next_input_byte+=number_bytes;
source->manager.bytes_in_buffer-=number_bytes;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 GraphicsContext::clipPath(const Path&, WindRule)
{
notImplemented();
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ext4_split_unwritten_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path,
int flags)
{
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= EXT4_EXT_MARK_UNINIT2;
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, path, map, split_flag, flags);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: bool venc_dev::venc_set_operatingrate(OMX_U32 rate) {
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE;
control.value = rate;
DEBUG_PRINT_LOW("venc_set_operating_rate: %d fps", rate >> 16);
DEBUG_PRINT_LOW("Calling IOCTL set control for id=%d, val=%d", control.id, control.value);
if(ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control)) {
hw_overload = errno == EBUSY;
DEBUG_PRINT_ERROR("Failed to set operating rate %d fps (%s)",
rate >> 16, hw_overload ? "HW overload" : strerror(errno));
return false;
}
operating_rate = rate;
DEBUG_PRINT_LOW("Operating Rate Set = %d fps", rate >> 16);
return true;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RenderBlock::paintAsInlineBlock(RenderObject* renderer, PaintInfo& paintInfo, const LayoutPoint& childPoint)
{
if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection)
return;
bool preservePhase = paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip;
PaintInfo info(paintInfo);
info.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
renderer->paint(info, childPoint);
if (!preservePhase) {
info.phase = PaintPhaseChildBlockBackgrounds;
renderer->paint(info, childPoint);
info.phase = PaintPhaseFloat;
renderer->paint(info, childPoint);
info.phase = PaintPhaseForeground;
renderer->paint(info, childPoint);
info.phase = PaintPhaseOutline;
renderer->paint(info, childPoint);
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
{
const struct usb_cdc_union_desc *union_desc;
struct usb_host_interface *alt;
union_desc = ims_pcu_get_cdc_union_desc(intf);
if (!union_desc)
return -EINVAL;
pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bMasterInterface0);
alt = pcu->ctrl_intf->cur_altsetting;
pcu->ep_ctrl = &alt->endpoint[0].desc;
pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
pcu->data_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bSlaveInterface0);
alt = pcu->data_intf->cur_altsetting;
if (alt->desc.bNumEndpoints != 2) {
dev_err(pcu->dev,
"Incorrect number of endpoints on data interface (%d)\n",
alt->desc.bNumEndpoints);
return -EINVAL;
}
pcu->ep_out = &alt->endpoint[0].desc;
if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
dev_err(pcu->dev,
"First endpoint on data interface is not BULK OUT\n");
return -EINVAL;
}
pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
if (pcu->max_out_size < 8) {
dev_err(pcu->dev,
"Max OUT packet size is too small (%zd)\n",
pcu->max_out_size);
return -EINVAL;
}
pcu->ep_in = &alt->endpoint[1].desc;
if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
dev_err(pcu->dev,
"Second endpoint on data interface is not BULK IN\n");
return -EINVAL;
}
pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
if (pcu->max_in_size < 8) {
dev_err(pcu->dev,
"Max IN packet size is too small (%zd)\n",
pcu->max_in_size);
return -EINVAL;
}
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: MockRenderProcess() {}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
QuicFecGroupNumber fec_group) {
header_.packet_sequence_number = number;
header_.flags = PACKET_FLAGS_NONE;
header_.fec_group = fec_group;
QuicFrames frames;
QuicFrame frame(&frame1_);
frames.push_back(frame);
QuicPacket* packet;
framer_.ConstructFragementDataPacket(header_, frames, &packet);
return packet;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) {
RConfigNode *node = NULL;
char *ov = NULL;
ut64 oi;
if (!cfg || STRNULL (name)) {
return NULL;
}
node = r_config_node_get (cfg, name);
if (node) {
if (node->flags & CN_RO) {
eprintf ("(error: '%s' config key is read only)\n", name);
return node;
}
oi = node->i_value;
if (node->value) {
ov = strdup (node->value);
if (!ov) {
goto beach;
}
} else {
free (node->value);
node->value = strdup ("");
}
if (node->flags & CN_BOOL) {
bool b = is_true (value);
node->i_value = (ut64) b? 1: 0;
char *value = strdup (r_str_bool (b));
if (value) {
free (node->value);
node->value = value;
}
} else {
if (!value) {
free (node->value);
node->value = strdup ("");
node->i_value = 0;
} else {
if (node->value == value) {
goto beach;
}
free (node->value);
node->value = strdup (value);
if (IS_DIGIT (*value)) {
if (strchr (value, '/')) {
node->i_value = r_num_get (cfg->num, value);
} else {
node->i_value = r_num_math (cfg->num, value);
}
} else {
node->i_value = 0;
}
node->flags |= CN_INT;
}
}
} else { // Create a new RConfigNode
oi = UT64_MAX;
if (!cfg->lock) {
node = r_config_node_new (name, value);
if (node) {
if (value && is_bool (value)) {
node->flags |= CN_BOOL;
node->i_value = is_true (value)? 1: 0;
}
if (cfg->ht) {
ht_insert (cfg->ht, node->name, node);
r_list_append (cfg->nodes, node);
cfg->n_nodes++;
}
} else {
eprintf ("r_config_set: unable to create a new RConfigNode\n");
}
} else {
eprintf ("r_config_set: variable '%s' not found\n", name);
}
}
if (node && node->setter) {
int ret = node->setter (cfg->user, node);
if (ret == false) {
if (oi != UT64_MAX) {
node->i_value = oi;
}
free (node->value);
node->value = strdup (ov? ov: "");
}
}
beach:
free (ov);
return node;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
const unsigned char **in, long inlen,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
int ret = 0, utype;
long plen;
char cst, inf, free_cont = 0;
const unsigned char *p;
BUF_MEM buf;
const unsigned char *cont = NULL;
long len;
if (!pval) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
return 0; /* Should never happen */
}
if (it->itype == ASN1_ITYPE_MSTRING) {
utype = tag;
tag = -1;
} else
utype = it->utype;
if (utype == V_ASN1_ANY) {
/* If type is ANY need to figure out type from tag */
unsigned char oclass;
if (tag >= 0) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
return 0;
}
if (opt) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
ASN1_R_ILLEGAL_OPTIONAL_ANY);
return 0;
}
p = *in;
ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
&p, inlen, -1, 0, 0, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
if (oclass != V_ASN1_UNIVERSAL)
utype = V_ASN1_OTHER;
}
if (tag == -1) {
tag = utype;
aclass = V_ASN1_UNIVERSAL;
}
p = *in;
/* Check header */
ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
&p, inlen, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
return 0;
} else if (ret == -1)
return -1;
ret = 0;
/* SEQUENCE, SET and "OTHER" are left in encoded form */
if ((utype == V_ASN1_SEQUENCE)
|| (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
/*
* Clear context cache for type OTHER because the auto clear when we
* have a exact match wont work
*/
if (utype == V_ASN1_OTHER) {
asn1_tlc_clear(ctx);
}
/* SEQUENCE and SET must be constructed */
else if (!cst) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
ASN1_R_TYPE_NOT_CONSTRUCTED);
return 0;
}
cont = *in;
/* If indefinite length constructed find the real end */
if (inf) {
if (!asn1_find_end(&p, plen, inf))
goto err;
len = p - cont;
} else {
len = p - cont + plen;
p += plen;
buf.data = NULL;
}
} else if (cst) {
if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
|| utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
|| utype == V_ASN1_ENUMERATED) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
}
buf.length = 0;
buf.max = 0;
buf.data = NULL;
/*
* Should really check the internal tags are correct but some things
* may get this wrong. The relevant specs say that constructed string
* types should be OCTET STRINGs internally irrespective of the type.
* So instead just check for UNIVERSAL class and ignore the tag.
*/
if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
free_cont = 1;
goto err;
}
len = buf.length;
/* Append a final null to string */
if (!BUF_MEM_grow_clean(&buf, len + 1)) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
return 0;
}
buf.data[len] = 0;
cont = (const unsigned char *)buf.data;
free_cont = 1;
} else {
cont = p;
len = plen;
p += plen;
}
/* We now have content length and type: translate into a structure */
if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
goto err;
*in = p;
ret = 1;
err:
if (free_cont && buf.data)
OPENSSL_free(buf.data);
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 DownloadItemImpl::RemoveObserver(Observer* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observers_.RemoveObserver(observer);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static double digitize(double value, int depth, int do_round)
{
/* 'value' is in the range 0 to 1, the result is the same value rounded to a
* multiple of the digitization factor - 8 or 16 bits depending on both the
* sample depth and the 'assume' setting. Digitization is normally by
* rounding and 'do_round' should be 1, if it is 0 the digitized value will
* be truncated.
*/
PNG_CONST unsigned int digitization_factor = (1U << depth) -1;
/* Limiting the range is done as a convenience to the caller - it's easier to
* do it once here than every time at the call site.
*/
if (value <= 0)
value = 0;
else if (value >= 1)
value = 1;
value *= digitization_factor;
if (do_round) value += .5;
return floor(value)/digitization_factor;
}
CWE ID:
Target: 1
Example 2:
Code: oldParseTest(const char *filename, const char *result,
const char *err ATTRIBUTE_UNUSED,
int options ATTRIBUTE_UNUSED) {
xmlDocPtr doc;
char *temp;
int res = 0;
nb_tests++;
/*
* base of the test, parse with the old API
*/
#ifdef LIBXML_SAX1_ENABLED
doc = xmlParseFile(filename);
#else
doc = xmlReadFile(filename, NULL, 0);
#endif
if (doc == NULL)
return(1);
temp = resultFilename(filename, "", ".res");
if (temp == NULL) {
fprintf(stderr, "out of memory\n");
fatalError();
}
xmlSaveFile(temp, doc);
if (compareFiles(temp, result)) {
res = 1;
}
xmlFreeDoc(doc);
/*
* Parse the saved result to make sure the round trip is okay
*/
#ifdef LIBXML_SAX1_ENABLED
doc = xmlParseFile(temp);
#else
doc = xmlReadFile(temp, NULL, 0);
#endif
if (doc == NULL)
return(1);
xmlSaveFile(temp, doc);
if (compareFiles(temp, result)) {
res = 1;
}
xmlFreeDoc(doc);
if (temp != NULL) {
unlink(temp);
free(temp);
}
return(res);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return send(socket->fd, buf, count, MSG_DONTWAIT);
}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: EncodedJSValue JSC_HOST_CALL JSTestObjConstructor::constructJSTestObj(ExecState* exec)
{
JSTestObjConstructor* castedThis = jsCast<JSTestObjConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> testCallback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
RefPtr<TestObj> object = TestObj::create(testCallback);
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void dwc3_prepare_one_trb_sg(struct dwc3_ep *dep,
struct dwc3_request *req)
{
struct scatterlist *sg = req->sg;
struct scatterlist *s;
int i;
for_each_sg(sg, s, req->num_pending_sgs, i) {
unsigned int length = req->request.length;
unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
unsigned int rem = length % maxp;
unsigned chain = true;
if (sg_is_last(s))
chain = false;
if (rem && usb_endpoint_dir_out(dep->endpoint.desc) && !chain) {
struct dwc3 *dwc = dep->dwc;
struct dwc3_trb *trb;
req->unaligned = true;
/* prepare normal TRB */
dwc3_prepare_one_trb(dep, req, true, i);
/* Now prepare one extra TRB to align transfer size */
trb = &dep->trb_pool[dep->trb_enqueue];
__dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr,
maxp - rem, false, 0,
req->request.stream_id,
req->request.short_not_ok,
req->request.no_interrupt);
} else {
dwc3_prepare_one_trb(dep, req, chain, i);
}
if (!dwc3_calc_trbs_left(dep))
break;
}
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 TabletModeWindowManager::ForgetWindow(aura::Window* window,
bool destroyed) {
added_windows_.erase(window);
window->RemoveObserver(this);
WindowToState::iterator it = window_state_map_.find(window);
if (it == window_state_map_.end())
return;
if (destroyed) {
window_state_map_.erase(it);
} else {
it->second->LeaveTabletMode(wm::GetWindowState(it->first));
DCHECK(!IsTrackingWindow(window));
}
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
int transhdrlen = 4; /* zero session-id */
int ulen = len + transhdrlen;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (lsa) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)
return -EAFNOSUPPORT;
daddr = &lsa->l2tp_addr;
if (np->sndflow) {
fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
lsa->l2tp_scope_id &&
ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)
fl6.flowi6_oif = lsa->l2tp_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (opt == NULL)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = sk->sk_protocol;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg,
ulen, transhdrlen, hlimit, tclass, opt,
&fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = l2tp_ip6_push_pending_frames(sk);
release_sock(sk);
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void mark_discard_range_all(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
int i;
mutex_lock(&dcc->cmd_lock);
for (i = 0; i < MAX_PLIST_NUM; i++)
dcc->pend_list_tag[i] |= P_TRIM;
mutex_unlock(&dcc->cmd_lock);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 __init acpi_custom_method_init(void)
{
if (!acpi_debugfs_dir)
return -ENOENT;
cm_dentry = debugfs_create_file("custom_method", S_IWUSR,
acpi_debugfs_dir, NULL, &cm_fops);
if (!cm_dentry)
return -ENODEV;
return 0;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response.Url());
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: MagickExport MagickBooleanType CloseBlob(Image *image)
{
BlobInfo
*magick_restrict blob_info;
int
status;
/*
Close image file.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
blob_info=image->blob;
if ((blob_info == (BlobInfo *) NULL) || (blob_info->type == UndefinedStream))
return(MagickTrue);
status=SyncBlob(image);
switch (blob_info->type)
{
case UndefinedStream:
case StandardStream:
break;
case FileStream:
case PipeStream:
{
if (blob_info->synchronize != MagickFalse)
status=fsync(fileno(blob_info->file_info.file));
status=ferror(blob_info->file_info.file);
break;
}
case ZipStream:
{
#if defined(MAGICKCORE_ZLIB_DELEGATE)
(void) gzerror(blob_info->file_info.gzfile,&status);
#endif
break;
}
case BZipStream:
{
#if defined(MAGICKCORE_BZLIB_DELEGATE)
(void) BZ2_bzerror(blob_info->file_info.bzfile,&status);
#endif
break;
}
case FifoStream:
break;
case BlobStream:
{
if (blob_info->file_info.file != (FILE *) NULL)
{
if (blob_info->synchronize != MagickFalse)
status=fsync(fileno(blob_info->file_info.file));
status=ferror(blob_info->file_info.file);
}
break;
}
case CustomStream:
break;
}
blob_info->status=status < 0 ? MagickTrue : MagickFalse;
blob_info->size=GetBlobSize(image);
image->extent=blob_info->size;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->mode=UndefinedBlobMode;
if (blob_info->exempt != MagickFalse)
{
blob_info->type=UndefinedStream;
return(blob_info->status);
}
switch (blob_info->type)
{
case UndefinedStream:
case StandardStream:
break;
case FileStream:
{
if (fileno(blob_info->file_info.file) != -1)
status=fclose(blob_info->file_info.file);
break;
}
case PipeStream:
{
#if defined(MAGICKCORE_HAVE_PCLOSE)
status=pclose(blob_info->file_info.file);
#endif
break;
}
case ZipStream:
{
#if defined(MAGICKCORE_ZLIB_DELEGATE)
status=gzclose(blob_info->file_info.gzfile);
#endif
break;
}
case BZipStream:
{
#if defined(MAGICKCORE_BZLIB_DELEGATE)
BZ2_bzclose(blob_info->file_info.bzfile);
#endif
break;
}
case FifoStream:
break;
case BlobStream:
{
if (blob_info->file_info.file != (FILE *) NULL)
status=fclose(blob_info->file_info.file);
break;
}
case CustomStream:
break;
}
(void) DetachBlob(blob_info);
blob_info->status=status < 0 ? MagickTrue : MagickFalse;
return(blob_info->status);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: poly_send(PG_FUNCTION_ARGS)
{
POLYGON *poly = PG_GETARG_POLYGON_P(0);
StringInfoData buf;
int32 i;
pq_begintypsend(&buf);
pq_sendint(&buf, poly->npts, sizeof(int32));
for (i = 0; i < poly->npts; i++)
{
pq_sendfloat8(&buf, poly->p[i].x);
pq_sendfloat8(&buf, poly->p[i].y);
}
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Cluster* BlockEntry::GetCluster() const
{
return m_pCluster;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline zend_bool check_str(const char *chk_str, size_t chk_len, const char *sep_str, size_t sep_len) {
return 0 < sep_len && chk_len >= sep_len && *chk_str == *sep_str && !memcmp(chk_str + 1, sep_str + 1, sep_len - 1);
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ChromeContentBrowserClient::GetDevToolsBackgroundServiceExpirations(
content::BrowserContext* browser_context) {
Profile* profile = Profile::FromBrowserContext(browser_context);
DCHECK(profile);
auto* pref_service = profile->GetPrefs();
DCHECK(pref_service);
auto* expiration_dict = pref_service->GetDictionary(
prefs::kDevToolsBackgroundServicesExpirationDict);
DCHECK(expiration_dict);
base::flat_map<int, base::Time> expiration_times;
for (const auto& it : *expiration_dict) {
int service = 0;
bool did_convert = base::StringToInt(it.first, &service);
DCHECK(did_convert);
DCHECK(it.second->is_int());
base::TimeDelta delta = base::TimeDelta::FromMinutes(it.second->GetInt());
base::Time expiration_time = base::Time::FromDeltaSinceWindowsEpoch(delta);
expiration_times[service] = expiration_time;
}
return expiration_times;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void NavigationRequest::SetOriginPolicy(const std::string& policy) {
common_params_.origin_policy = policy;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: unsigned long netdev_increment_features(unsigned long all, unsigned long one,
unsigned long mask)
{
/* If device needs checksumming, downgrade to it. */
if (all & NETIF_F_NO_CSUM && !(one & NETIF_F_NO_CSUM))
all ^= NETIF_F_NO_CSUM | (one & NETIF_F_ALL_CSUM);
else if (mask & NETIF_F_ALL_CSUM) {
/* If one device supports v4/v6 checksumming, set for all. */
if (one & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM) &&
!(all & NETIF_F_GEN_CSUM)) {
all &= ~NETIF_F_ALL_CSUM;
all |= one & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
}
/* If one device supports hw checksumming, set for all. */
if (one & NETIF_F_GEN_CSUM && !(all & NETIF_F_GEN_CSUM)) {
all &= ~NETIF_F_ALL_CSUM;
all |= NETIF_F_HW_CSUM;
}
}
one |= NETIF_F_ALL_CSUM;
one |= all & NETIF_F_ONE_FOR_ALL;
all &= one | NETIF_F_LLTX | NETIF_F_GSO | NETIF_F_UFO;
all |= one & mask & NETIF_F_ONE_FOR_ALL;
return all;
}
CWE ID: CWE-399
Output: | 0 |
Subsets and Splits