instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midibuffer == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0);
return (NULL);
}
if (size > WM_MAXFILESIZE) {
/* don't bother loading suspiciously long files */
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0);
return (NULL);
}
if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(midibuffer, size);
} else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(midibuffer, size);
} else if (memcmp(midibuffer, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(midibuffer, size);
} else if (memcmp(midibuffer, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(midibuffer, size);
} else {
ret = (void *) _WM_ParseNewMidi(midibuffer, size);
}
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input
Fixes bug #178.
CWE ID: CWE-119
|
WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midibuffer == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0);
return (NULL);
}
if (size > WM_MAXFILESIZE) {
/* don't bother loading suspiciously long files */
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0);
return (NULL);
}
if (size < 18) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(midibuffer, size);
} else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(midibuffer, size);
} else if (memcmp(midibuffer, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(midibuffer, size);
} else if (memcmp(midibuffer, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(midibuffer, size);
} else {
ret = (void *) _WM_ParseNewMidi(midibuffer, size);
}
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
| 169,370
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)
{
switch (whence)
{ case SEEK_SET :
if (position > SIGNED_SIZEOF (psf->header))
{ /* Too much header to cache so just seek instead. */
psf_fseek (psf, position, whence) ;
return ;
} ;
if (position > psf->headend)
psf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ;
psf->headindex = position ;
break ;
case SEEK_CUR :
if (psf->headindex + position < 0)
break ;
if (psf->headindex >= SIGNED_SIZEOF (psf->header))
{ psf_fseek (psf, position, whence) ;
return ;
} ;
if (psf->headindex + position <= psf->headend)
{ psf->headindex += position ;
break ;
} ;
if (psf->headindex + position > SIGNED_SIZEOF (psf->header))
{ /* Need to jump this without caching it. */
psf->headindex = psf->headend ;
psf_fseek (psf, position, SEEK_CUR) ;
break ;
} ;
psf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ;
psf->headindex = psf->headend ;
break ;
case SEEK_END :
default :
psf_log_printf (psf, "Bad whence param in header_seek().\n") ;
break ;
} ;
return ;
} /* header_seek */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
|
header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)
{
switch (whence)
{ case SEEK_SET :
if (psf->header.indx + position >= psf->header.len)
psf_bump_header_allocation (psf, position) ;
if (position > psf->header.len)
{ /* Too much header to cache so just seek instead. */
psf_fseek (psf, position, whence) ;
return ;
} ;
if (position > psf->header.end)
psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, position - psf->header.end, psf) ;
psf->header.indx = position ;
break ;
case SEEK_CUR :
if (psf->header.indx + position >= psf->header.len)
psf_bump_header_allocation (psf, position) ;
if (psf->header.indx + position < 0)
break ;
if (psf->header.indx >= psf->header.len)
{ psf_fseek (psf, position, whence) ;
return ;
} ;
if (psf->header.indx + position <= psf->header.end)
{ psf->header.indx += position ;
break ;
} ;
if (psf->header.indx + position > psf->header.len)
{ /* Need to jump this without caching it. */
psf->header.indx = psf->header.end ;
psf_fseek (psf, position, SEEK_CUR) ;
break ;
} ;
psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, position - (psf->header.end - psf->header.indx), psf) ;
psf->header.indx = psf->header.end ;
break ;
case SEEK_END :
default :
psf_log_printf (psf, "Bad whence param in header_seek().\n") ;
break ;
} ;
return ;
} /* header_seek */
| 170,062
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t Camera3Device::createDefaultRequest(int templateId,
CameraMetadata *request) {
ATRACE_CALL();
ALOGV("%s: for template %d", __FUNCTION__, templateId);
Mutex::Autolock il(mInterfaceLock);
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device is not initialized!");
return INVALID_OPERATION;
case STATUS_UNCONFIGURED:
case STATUS_CONFIGURED:
case STATUS_ACTIVE:
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
if (!mRequestTemplateCache[templateId].isEmpty()) {
*request = mRequestTemplateCache[templateId];
return OK;
}
const camera_metadata_t *rawRequest;
ATRACE_BEGIN("camera3->construct_default_request_settings");
rawRequest = mHal3Device->ops->construct_default_request_settings(
mHal3Device, templateId);
ATRACE_END();
if (rawRequest == NULL) {
ALOGI("%s: template %d is not supported on this camera device",
__FUNCTION__, templateId);
return BAD_VALUE;
}
*request = rawRequest;
mRequestTemplateCache[templateId] = rawRequest;
return OK;
}
Commit Message: Camera3Device: Validate template ID
Validate template ID before creating a default request.
Bug: 26866110
Bug: 27568958
Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d
CWE ID: CWE-264
|
status_t Camera3Device::createDefaultRequest(int templateId,
CameraMetadata *request) {
ATRACE_CALL();
ALOGV("%s: for template %d", __FUNCTION__, templateId);
if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
IPCThreadState::self()->getCallingUid(), NULL, 0);
return BAD_VALUE;
}
Mutex::Autolock il(mInterfaceLock);
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device is not initialized!");
return INVALID_OPERATION;
case STATUS_UNCONFIGURED:
case STATUS_CONFIGURED:
case STATUS_ACTIVE:
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
if (!mRequestTemplateCache[templateId].isEmpty()) {
*request = mRequestTemplateCache[templateId];
return OK;
}
const camera_metadata_t *rawRequest;
ATRACE_BEGIN("camera3->construct_default_request_settings");
rawRequest = mHal3Device->ops->construct_default_request_settings(
mHal3Device, templateId);
ATRACE_END();
if (rawRequest == NULL) {
ALOGI("%s: template %d is not supported on this camera device",
__FUNCTION__, templateId);
return BAD_VALUE;
}
*request = rawRequest;
mRequestTemplateCache[templateId] = rawRequest;
return OK;
}
| 173,883
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
JBIG2Segment(segNumA)
{
w = wA;
h = hA;
line = (wA + 7) >> 3;
if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
error(-1, "invalid width/height");
data = NULL;
return;
}
data = (Guchar *)gmalloc(h * line + 1);
data[h * line] = 0;
}
Commit Message:
CWE ID: CWE-189
|
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
JBIG2Segment(segNumA)
{
w = wA;
h = hA;
line = (wA + 7) >> 3;
if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
error(-1, "invalid width/height");
data = NULL;
return;
}
data = (Guchar *)gmallocn(h, line + 1);
data[h * line] = 0;
}
| 164,612
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: png_get_uint_16(png_bytep buf)
{
png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
(png_uint_16)(*(buf + 1)));
return (i);
}
Commit Message: third_party/libpng: update to 1.2.54
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
|
png_get_uint_16(png_bytep buf)
{
png_uint_16 i = ((png_uint_16)((*(buf )) & 0xff) << 8) +
((png_uint_16)((*(buf + 1)) & 0xff) );
return (i);
}
| 172,174
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(xml_parser_create)
{
php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
Commit Message:
CWE ID: CWE-119
|
PHP_FUNCTION(xml_parser_create)
{
php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
| 165,035
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
| 167,119
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
{
major = 1;
minor = 0;
build = 0;
revision = 27;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
| 174,379
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ResourceDispatcherHostImpl::PauseRequest(int child_id,
int request_id,
bool pause) {
GlobalRequestID global_id(child_id, request_id);
PendingRequestList::iterator i = pending_requests_.find(global_id);
if (i == pending_requests_.end()) {
DVLOG(1) << "Pausing a request that wasn't found";
return;
}
ResourceRequestInfoImpl* info =
ResourceRequestInfoImpl::ForRequest(i->second);
int pause_count = info->pause_count() + (pause ? 1 : -1);
if (pause_count < 0) {
NOTREACHED(); // Unbalanced call to pause.
return;
}
info->set_pause_count(pause_count);
VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec();
if (info->pause_count() == 0) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(
&ResourceDispatcherHostImpl::ResumeRequest,
weak_factory_.GetWeakPtr(),
global_id));
}
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void ResourceDispatcherHostImpl::PauseRequest(int child_id,
int request_id,
bool pause) {
GlobalRequestID global_id(child_id, request_id);
PendingRequestList::iterator i = pending_requests_.find(global_id);
if (i == pending_requests_.end()) {
DVLOG(1) << "Pausing a request that wasn't found";
return;
}
ResourceRequestInfoImpl* info =
ResourceRequestInfoImpl::ForRequest(i->second);
int pause_count = info->pause_count() + (pause ? 1 : -1);
if (pause_count < 0) {
NOTREACHED(); // Unbalanced call to pause.
return;
}
info->set_pause_count(pause_count);
VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec();
if (info->pause_count() == 0) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(&ResourceDispatcherHostImpl::ResumeRequest,
AsWeakPtr(), global_id));
}
}
| 170,990
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: StorageHandler::GetCacheStorageObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!cache_storage_observer_) {
cache_storage_observer_ = std::make_unique<CacheStorageObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<CacheStorageContextImpl*>(
process_->GetStoragePartition()->GetCacheStorageContext()));
}
return cache_storage_observer_.get();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
StorageHandler::GetCacheStorageObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!cache_storage_observer_) {
cache_storage_observer_ = std::make_unique<CacheStorageObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<CacheStorageContextImpl*>(
storage_partition_->GetCacheStorageContext()));
}
return cache_storage_observer_.get();
}
| 172,771
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ObjectBackedNativeHandler::Router(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> handler_function_value;
v8::Local<v8::Value> feature_name_value;
if (!GetPrivate(context, data, kHandlerFunction, &handler_function_value) ||
handler_function_value->IsUndefined() ||
!GetPrivate(context, data, kFeatureName, &feature_name_value) ||
!feature_name_value->IsString()) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
console::Error(script_context ? script_context->GetRenderFrame() : nullptr,
"Extension view no longer exists");
return;
}
if (content::WorkerThread::GetCurrentId() == 0) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
v8::Local<v8::String> feature_name_string =
feature_name_value->ToString(context).ToLocalChecked();
std::string feature_name = *v8::String::Utf8Value(feature_name_string);
if (script_context &&
!feature_name.empty() &&
!script_context->GetAvailability(feature_name).is_available()) {
return;
}
}
CHECK(handler_function_value->IsExternal());
static_cast<HandlerFunction*>(
handler_function_value.As<v8::External>()->Value())->Run(args);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
v8::Local<v8::Value> ret_value = ret.Get();
if (ret_value->IsObject() && !ret_value->IsNull() &&
!ContextCanAccessObject(context, v8::Local<v8::Object>::Cast(ret_value),
true)) {
NOTREACHED() << "Insecure return value";
ret.SetUndefined();
}
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
|
void ObjectBackedNativeHandler::Router(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> handler_function_value;
v8::Local<v8::Value> feature_name_value;
if (!GetPrivate(context, data, kHandlerFunction, &handler_function_value) ||
handler_function_value->IsUndefined() ||
!GetPrivate(context, data, kFeatureName, &feature_name_value) ||
!feature_name_value->IsString()) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
console::Error(script_context ? script_context->GetRenderFrame() : nullptr,
"Extension view no longer exists");
return;
}
if (content::WorkerThread::GetCurrentId() == 0) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
v8::Local<v8::String> feature_name_string =
feature_name_value->ToString(context).ToLocalChecked();
std::string feature_name = *v8::String::Utf8Value(feature_name_string);
if (script_context && !feature_name.empty()) {
Feature::Availability availability =
script_context->GetAvailability(feature_name);
if (!availability.is_available()) {
DVLOG(1) << feature_name
<< " is not available: " << availability.message();
return;
}
}
}
CHECK(handler_function_value->IsExternal());
static_cast<HandlerFunction*>(
handler_function_value.As<v8::External>()->Value())->Run(args);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
v8::Local<v8::Value> ret_value = ret.Get();
if (ret_value->IsObject() && !ret_value->IsNull() &&
!ContextCanAccessObject(context, v8::Local<v8::Object>::Cast(ret_value),
true)) {
NOTREACHED() << "Insecure return value";
ret.SetUndefined();
}
}
| 172,251
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ProcessControlLaunched() {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
#if defined(OS_WIN)
service_process_ =
base::Process::OpenWithAccess(service_pid,
SYNCHRONIZE | PROCESS_QUERY_INFORMATION);
#else
service_process_ = base::Process::Open(service_pid);
#endif
EXPECT_TRUE(service_process_.IsValid());
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated().
Bug: 844016
Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0
Reviewed-on: https://chromium-review.googlesource.com/1126576
Commit-Queue: Wez <wez@chromium.org>
Reviewed-by: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#573131}
CWE ID: CWE-94
|
void ProcessControlLaunched() {
void ProcessControlLaunched(base::OnceClosure on_done) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
#if defined(OS_WIN)
service_process_ =
base::Process::OpenWithAccess(service_pid,
SYNCHRONIZE | PROCESS_QUERY_INFORMATION);
#else
service_process_ = base::Process::Open(service_pid);
#endif
EXPECT_TRUE(service_process_.IsValid());
std::move(on_done).Run();
}
| 172,053
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
ptr++; /* skip "Reserved" */
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
l2tp_accm_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ptr++; /* skip "Reserved" */
length -= 2;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2;
val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
| 167,889
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SendNotImplementedError(struct mg_connection* connection,
const struct mg_request_info* request_info,
void* user_data) {
std::string body = base::StringPrintf(
"{\"status\":%d,\"value\":{\"message\":"
"\"Command has not been implemented yet: %s %s\"}}",
kUnknownCommand, request_info->request_method, request_info->uri);
std::string header = base::StringPrintf(
"HTTP/1.1 501 Not Implemented\r\n"
"Content-Type:application/json\r\n"
"Content-Length:%" PRIuS "\r\n"
"\r\n", body.length());
LOG(ERROR) << header << body;
mg_write(connection, header.data(), header.length());
mg_write(connection, body.data(), body.length());
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void SendNotImplementedError(struct mg_connection* connection,
const struct mg_request_info* request_info,
void* user_data) {
std::string body = base::StringPrintf(
"{\"status\":%d,\"value\":{\"message\":"
"\"Command has not been implemented yet: %s %s\"}}",
kUnknownCommand, request_info->request_method, request_info->uri);
std::string header = base::StringPrintf(
"HTTP/1.1 501 Not Implemented\r\n"
"Content-Type:application/json\r\n"
"Content-Length:%" PRIuS "\r\n"
"\r\n", body.length());
mg_write(connection, header.data(), header.length());
mg_write(connection, body.data(), body.length());
}
| 170,457
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: explicit MountState(DriveFsHost* host)
: host_(host),
mojo_connection_delegate_(
host_->delegate_->CreateMojoConnectionDelegate()),
pending_token_(base::UnguessableToken::Create()),
binding_(this) {
source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()});
std::string datadir_option = base::StrCat(
{"datadir=",
host_->profile_path_.Append(kDataPath)
.Append(host_->delegate_->GetAccountId().GetAccountIdKey())
.value()});
chromeos::disks::DiskMountManager::GetInstance()->MountPath(
source_path_, "",
base::StrCat(
{"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}),
{datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE,
chromeos::MOUNT_ACCESS_MODE_READ_WRITE);
auto bootstrap =
mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection());
mojom::DriveFsDelegatePtr delegate;
binding_.Bind(mojo::MakeRequest(&delegate));
bootstrap->Init(
{base::in_place, host_->delegate_->GetAccountId().GetUserEmail()},
mojo::MakeRequest(&drivefs_), std::move(delegate));
PendingConnectionManager::Get().ExpectOpenIpcChannel(
pending_token_,
base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection,
base::Unretained(this)));
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <xiyuan@chromium.org>
Commit-Queue: Sam McNally <sammc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID:
|
explicit MountState(DriveFsHost* host)
: host_(host),
mojo_connection_delegate_(
host_->delegate_->CreateMojoConnectionDelegate()),
pending_token_(base::UnguessableToken::Create()),
binding_(this) {
source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()});
std::string datadir_option = base::StrCat(
{"datadir=",
host_->profile_path_.Append(kDataPath)
.Append(host_->delegate_->GetAccountId().GetAccountIdKey())
.value()});
auto bootstrap =
mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection());
mojom::DriveFsDelegatePtr delegate;
binding_.Bind(mojo::MakeRequest(&delegate));
bootstrap->Init(
{base::in_place, host_->delegate_->GetAccountId().GetUserEmail()},
mojo::MakeRequest(&drivefs_), std::move(delegate));
PendingConnectionManager::Get().ExpectOpenIpcChannel(
pending_token_,
base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection,
base::Unretained(this)));
chromeos::disks::DiskMountManager::GetInstance()->MountPath(
source_path_, "",
base::StrCat(
{"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}),
{datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE,
chromeos::MOUNT_ACCESS_MODE_READ_WRITE);
}
| 171,729
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: DOMHandler::DOMHandler()
: DevToolsDomainHandler(DOM::Metainfo::domainName),
host_(nullptr) {
}
Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles
Bug: 805557
Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f
Reviewed-on: https://chromium-review.googlesource.com/c/1334847
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Commit-Queue: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#607902}
CWE ID: CWE-254
|
DOMHandler::DOMHandler()
DOMHandler::DOMHandler(bool allow_file_access)
: DevToolsDomainHandler(DOM::Metainfo::domainName),
| 173,112
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
Commit Message: Merge some file writing extension checks from OpenJK.
Thanks Ensiform.
https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0
https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176
CWE ID: CWE-269
|
void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
| 170,077
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
}
Commit Message: SWFShape_setLeftFillStyle: prevent fill overflow
CWE ID: CWE-119
|
SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
else if (idx >= 255 && shape->useVersion == SWF_SHAPE1)
{
SWF_error("Too many fills for SWFShape V1.\n"
"Use a higher SWFShape version\n");
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
}
| 169,647
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del(&pin->m_list);
hlist_del(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
}
Commit Message: fs_pin: Allow for the possibility that m_list or s_list go unused.
This is needed to support lazily umounting locked mounts. Because the
entire unmounted subtree needs to stay together until there are no
users with references to any part of the subtree.
To support this guarantee that the fs_pin m_list and s_list nodes
are initialized by initializing them in init_fs_pin allowing
for the possibility that pin_insert_group does not touch them.
Further use hlist_del_init in pin_remove so that there is
a hlist_unhashed test before the list we attempt to update
the previous list item.
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
CWE ID:
|
void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del_init(&pin->m_list);
hlist_del_init(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
}
| 167,562
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PassRefPtrWillBeRawPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
KURL fileSystemURL = createFileSystemURL(fileEntry);
RefPtrWillBeRawPtr<CreateFileHelper::CreateFileResult> result(CreateFileHelper::CreateFileResult::create());
fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type()));
if (result->m_failed) {
exceptionState.throwDOMException(result->m_code, "Could not create '" + fileEntry->name() + "'.");
return nullptr;
}
return result->m_file.get();
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
PassRefPtrWillBeRawPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState)
{
KURL fileSystemURL = createFileSystemURL(fileEntry);
CreateFileHelper::CreateFileResult* result(CreateFileHelper::CreateFileResult::create());
fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type()));
if (result->m_failed) {
exceptionState.throwDOMException(result->m_code, "Could not create '" + fileEntry->name() + "'.");
return nullptr;
}
return result->m_file.get();
}
| 171,415
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const
{
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const
| 174,380
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SyncManager::MaybeSetSyncTabsInNigoriNode(
ModelTypeSet enabled_types) {
DCHECK(thread_checker_.CalledOnValidThread());
data_->MaybeSetSyncTabsInNigoriNode(enabled_types);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
void SyncManager::MaybeSetSyncTabsInNigoriNode(
| 170,794
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Tracks::~Tracks()
{
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
delete pTrack;
}
delete[] m_trackEntries;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Tracks::~Tracks()
| 174,473
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: check_interlace_type(int PNG_CONST interlace_type)
{
if (interlace_type != PNG_INTERLACE_NONE)
{
/* This is an internal error - --interlace tests should be skipped, not
* attempted.
*/
fprintf(stderr, "pngvalid: no interlace support\n");
exit(99);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
check_interlace_type(int PNG_CONST interlace_type)
check_interlace_type(int const interlace_type)
{
/* Prior to 1.7.0 libpng does not support the write of an interlaced image
* unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
* code here does the pixel interlace itself, so:
*/
if (interlace_type != PNG_INTERLACE_NONE)
{
/* This is an internal error - --interlace tests should be skipped, not
* attempted.
*/
fprintf(stderr, "pngvalid: no interlace support\n");
exit(99);
}
}
| 173,605
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CairoOutputDev::beginString(GfxState *state, GooString *s)
{
int len = s->getLength();
if (needFontUpdate)
updateFont(state);
if (!currentFont)
return;
glyphs = (cairo_glyph_t *) gmalloc (len * sizeof (cairo_glyph_t));
glyphCount = 0;
}
Commit Message:
CWE ID: CWE-189
|
void CairoOutputDev::beginString(GfxState *state, GooString *s)
{
int len = s->getLength();
if (needFontUpdate)
updateFont(state);
if (!currentFont)
return;
glyphs = (cairo_glyph_t *) gmallocn (len, sizeof (cairo_glyph_t));
glyphCount = 0;
}
| 164,604
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) {
return v8::FunctionTemplate::New(GetExtensionAPIDefinition);
} else if (name->Equals(v8::String::New("GetExtensionViews"))) {
return v8::FunctionTemplate::New(GetExtensionViews,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetNextRequestId"))) {
return v8::FunctionTemplate::New(GetNextRequestId);
} else if (name->Equals(v8::String::New("OpenChannelToTab"))) {
return v8::FunctionTemplate::New(OpenChannelToTab);
} else if (name->Equals(v8::String::New("GetNextContextMenuId"))) {
return v8::FunctionTemplate::New(GetNextContextMenuId);
} else if (name->Equals(v8::String::New("GetCurrentPageActions"))) {
return v8::FunctionTemplate::New(GetCurrentPageActions,
v8::External::New(this));
} else if (name->Equals(v8::String::New("StartRequest"))) {
return v8::FunctionTemplate::New(StartRequest,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetRenderViewId"))) {
return v8::FunctionTemplate::New(GetRenderViewId);
} else if (name->Equals(v8::String::New("SetIconCommon"))) {
return v8::FunctionTemplate::New(SetIconCommon,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsExtensionProcess"))) {
return v8::FunctionTemplate::New(IsExtensionProcess,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsIncognitoProcess"))) {
return v8::FunctionTemplate::New(IsIncognitoProcess);
} else if (name->Equals(v8::String::New("GetUniqueSubEventName"))) {
return v8::FunctionTemplate::New(GetUniqueSubEventName);
} else if (name->Equals(v8::String::New("GetLocalFileSystem"))) {
return v8::FunctionTemplate::New(GetLocalFileSystem);
} else if (name->Equals(v8::String::New("DecodeJPEG"))) {
return v8::FunctionTemplate::New(DecodeJPEG, v8::External::New(this));
}
return ExtensionBase::GetNativeFunction(name);
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) {
return v8::FunctionTemplate::New(GetExtensionAPIDefinition);
} else if (name->Equals(v8::String::New("GetExtensionViews"))) {
return v8::FunctionTemplate::New(GetExtensionViews,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetNextRequestId"))) {
return v8::FunctionTemplate::New(GetNextRequestId);
} else if (name->Equals(v8::String::New("OpenChannelToTab"))) {
return v8::FunctionTemplate::New(OpenChannelToTab);
} else if (name->Equals(v8::String::New("GetNextContextMenuId"))) {
return v8::FunctionTemplate::New(GetNextContextMenuId);
} else if (name->Equals(v8::String::New("GetNextTtsEventId"))) {
return v8::FunctionTemplate::New(GetNextTtsEventId);
} else if (name->Equals(v8::String::New("GetCurrentPageActions"))) {
return v8::FunctionTemplate::New(GetCurrentPageActions,
v8::External::New(this));
} else if (name->Equals(v8::String::New("StartRequest"))) {
return v8::FunctionTemplate::New(StartRequest,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetRenderViewId"))) {
return v8::FunctionTemplate::New(GetRenderViewId);
} else if (name->Equals(v8::String::New("SetIconCommon"))) {
return v8::FunctionTemplate::New(SetIconCommon,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsExtensionProcess"))) {
return v8::FunctionTemplate::New(IsExtensionProcess,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsIncognitoProcess"))) {
return v8::FunctionTemplate::New(IsIncognitoProcess);
} else if (name->Equals(v8::String::New("GetUniqueSubEventName"))) {
return v8::FunctionTemplate::New(GetUniqueSubEventName);
} else if (name->Equals(v8::String::New("GetLocalFileSystem"))) {
return v8::FunctionTemplate::New(GetLocalFileSystem);
} else if (name->Equals(v8::String::New("DecodeJPEG"))) {
return v8::FunctionTemplate::New(DecodeJPEG, v8::External::New(this));
}
return ExtensionBase::GetNativeFunction(name);
}
| 170,404
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: OMXNodeInstance::OMXNodeInstance(
OMX *owner, const sp<IOMXObserver> &observer, const char *name)
: mOwner(owner),
mNodeID(0),
mHandle(NULL),
mObserver(observer),
mDying(false),
mBufferIDCount(0)
{
mName = ADebug::GetDebugName(name);
DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug");
ALOGV("debug level for %s is %d", name, DEBUG);
DEBUG_BUMP = DEBUG;
mNumPortBuffers[0] = 0;
mNumPortBuffers[1] = 0;
mDebugLevelBumpPendingBuffers[0] = 0;
mDebugLevelBumpPendingBuffers[1] = 0;
mMetadataType[0] = kMetadataBufferTypeInvalid;
mMetadataType[1] = kMetadataBufferTypeInvalid;
mSecureBufferType[0] = kSecureBufferTypeUnknown;
mSecureBufferType[1] = kSecureBufferTypeUnknown;
mIsSecure = AString(name).endsWith(".secure");
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
OMXNodeInstance::OMXNodeInstance(
OMX *owner, const sp<IOMXObserver> &observer, const char *name)
: mOwner(owner),
mNodeID(0),
mHandle(NULL),
mObserver(observer),
mDying(false),
mSailed(false),
mQueriedProhibitedExtensions(false),
mBufferIDCount(0)
{
mName = ADebug::GetDebugName(name);
DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug");
ALOGV("debug level for %s is %d", name, DEBUG);
DEBUG_BUMP = DEBUG;
mNumPortBuffers[0] = 0;
mNumPortBuffers[1] = 0;
mDebugLevelBumpPendingBuffers[0] = 0;
mDebugLevelBumpPendingBuffers[1] = 0;
mMetadataType[0] = kMetadataBufferTypeInvalid;
mMetadataType[1] = kMetadataBufferTypeInvalid;
mSecureBufferType[0] = kSecureBufferTypeUnknown;
mSecureBufferType[1] = kSecureBufferTypeUnknown;
mIsSecure = AString(name).endsWith(".secure");
}
| 174,129
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* input string encoded in utf-8 */
PyObject *visual = NULL; /* output string encoded in utf-8 */
PyObject *result = NULL; /* unicode output string */
int length = PyUnicode_GET_SIZE (unicode);
logical = PyUnicode_AsUTF8String (unicode);
if (logical == NULL)
goto cleanup;
visual = log2vis_utf8 (logical, length, base_direction, clean, reordernsm);
if (visual == NULL)
goto cleanup;
result = PyUnicode_DecodeUTF8 (PyString_AS_STRING (visual),
PyString_GET_SIZE (visual), "strict");
cleanup:
Py_XDECREF (logical);
Py_XDECREF (visual);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119
|
log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)
{
PyUnicodeObject *logical = NULL; /* input unicode or string object */
FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */
int clean = 0; /* optional flag to clean the string */
int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/
static char *kwargs[] =
{ "logical", "base_direction", "clean", "reordernsm", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kw, "U|iii", kwargs,
&logical, &base, &clean, &reordernsm)) {
return NULL;
}
/* Validate base */
if (!(base == FRIBIDI_TYPE_RTL
|| base == FRIBIDI_TYPE_LTR
|| base == FRIBIDI_TYPE_ON)) {
return PyErr_Format (PyExc_ValueError,
"invalid value %d: use either RTL, LTR or ON",
base);
}
return unicode_log2vis (logical, base, clean, reordernsm);
}
| 165,641
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for(;;)
put_chunk(unknown, sizeof unknown);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for (;;)
put_chunk(unknown, sizeof unknown);
}
| 173,577
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SetPreviewDataForIndex(int index, const base::RefCountedBytes* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
page_data_map_[index] = const_cast<base::RefCountedBytes*>(data);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void SetPreviewDataForIndex(int index, const base::RefCountedBytes* data) {
if (IsInvalidIndex(index))
return;
page_data_map_[index] = const_cast<base::RefCountedBytes*>(data);
}
| 170,825
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_METHOD(Phar, offsetExists)
{
char *fname;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_FALSE;
}
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
/* none of these are real files, so they don't exist */
RETURN_FALSE;
}
RETURN_TRUE;
} else {
if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, offsetExists)
{
char *fname;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_FALSE;
}
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
/* none of these are real files, so they don't exist */
RETURN_FALSE;
}
RETURN_TRUE;
} else {
if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
}
| 165,065
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
memcpy (res, dbg_data, nb10sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
|
static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
// memcpy (res, dbg_data, nb10sz);
// res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
| 169,229
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
ssize_t bytes_written;
int ret;
dprintk("%s: write %Zd bytes\n", bd->name, count);
bsg_set_block(bd, file);
bytes_written = 0;
ret = __bsg_write(bd, buf, count, &bytes_written,
file->f_mode & FMODE_WRITE);
*ppos = bytes_written;
/*
* return bytes written on non-fatal errors
*/
if (!bytes_written || err_block_err(ret))
bytes_written = ret;
dprintk("%s: returning %Zd\n", bd->name, bytes_written);
return bytes_written;
}
Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS
Both damn things interpret userland pointers embedded into the payload;
worse, they are actually traversing those. Leaving aside the bad
API design, this is very much _not_ safe to call with KERNEL_DS.
Bail out early if that happens.
Cc: stable@vger.kernel.org
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-416
|
bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
ssize_t bytes_written;
int ret;
dprintk("%s: write %Zd bytes\n", bd->name, count);
if (unlikely(segment_eq(get_fs(), KERNEL_DS)))
return -EINVAL;
bsg_set_block(bd, file);
bytes_written = 0;
ret = __bsg_write(bd, buf, count, &bytes_written,
file->f_mode & FMODE_WRITE);
*ppos = bytes_written;
/*
* return bytes written on non-fatal errors
*/
if (!bytes_written || err_block_err(ret))
bytes_written = ret;
dprintk("%s: returning %Zd\n", bd->name, bytes_written);
return bytes_written;
}
| 166,840
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int btsock_thread_wakeup(int h)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h);
return FALSE;
}
sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0};
return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
int btsock_thread_wakeup(int h)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h);
return FALSE;
}
sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0};
return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd);
}
| 173,464
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool TokenExitsSVG(const CompactHTMLToken& token) {
return DeprecatedEqualIgnoringCase(token.Data(),
SVGNames::foreignObjectTag.LocalName());
}
Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator.
HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML
integration point. This CL adds <annotation-xml>, <desc>, and SVG
<title>.
Bug: 805924
Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2
Reviewed-on: https://chromium-review.googlesource.com/964038
Commit-Queue: Kent Tamura <tkent@chromium.org>
Reviewed-by: Kouhei Ueno <kouhei@chromium.org>
Cr-Commit-Position: refs/heads/master@{#543634}
CWE ID: CWE-79
|
static bool TokenExitsSVG(const CompactHTMLToken& token) {
| 173,255
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context)
{
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false;
if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false;
return asn1_pop_tag(data);
}
| 164,586
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
}
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more
CWE ID: CWE-284
|
void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
unlink(RUN_LIB_FILE);
}
| 169,657
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
bool is_guest_view_hack)
: host_(RenderWidgetHostImpl::From(host)),
window_(nullptr),
in_shutdown_(false),
in_bounds_changed_(false),
popup_parent_host_view_(nullptr),
popup_child_host_view_(nullptr),
is_loading_(false),
has_composition_text_(false),
background_color_(SK_ColorWHITE),
needs_begin_frames_(false),
needs_flush_input_(false),
added_frame_observer_(false),
cursor_visibility_state_in_renderer_(UNKNOWN),
#if defined(OS_WIN)
legacy_render_widget_host_HWND_(nullptr),
legacy_window_destroyed_(false),
virtual_keyboard_requested_(false),
#endif
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
weak_ptr_factory_(this) {
if (!is_guest_view_hack_)
host_->SetView(this);
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
SetOverscrollControllerEnabled(overscroll_enabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
RenderViewHost* rvh = RenderViewHost::From(host_);
if (rvh) {
ignore_result(rvh->GetWebkitPreferences());
}
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
TBR=jam@chromium.org
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254
|
RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
bool is_guest_view_hack)
: host_(RenderWidgetHostImpl::From(host)),
window_(nullptr),
in_shutdown_(false),
in_bounds_changed_(false),
popup_parent_host_view_(nullptr),
popup_child_host_view_(nullptr),
is_loading_(false),
has_composition_text_(false),
background_color_(SK_ColorWHITE),
needs_begin_frames_(false),
needs_flush_input_(false),
added_frame_observer_(false),
cursor_visibility_state_in_renderer_(UNKNOWN),
#if defined(OS_WIN)
legacy_render_widget_host_HWND_(nullptr),
legacy_window_destroyed_(false),
virtual_keyboard_requested_(false),
#endif
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
frame_sink_id_(host_->AllocateFrameSinkId(is_guest_view_hack_)),
weak_ptr_factory_(this) {
if (!is_guest_view_hack_)
host_->SetView(this);
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
SetOverscrollControllerEnabled(overscroll_enabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
RenderViewHost* rvh = RenderViewHost::From(host_);
if (rvh) {
ignore_result(rvh->GetWebkitPreferences());
}
}
| 172,235
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void addArgumentToVtab(Parse *pParse){
if( pParse->sArg.z && pParse->pNewTable ){
const char *z = (const char*)pParse->sArg.z;
int n = pParse->sArg.n;
sqlite3 *db = pParse->db;
addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
}
}
Commit Message: sqlite: backport bugfixes for dbfuzz2
Bug: 952406
Change-Id: Icbec429742048d6674828726c96d8e265c41b595
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152
Reviewed-by: Chris Mumford <cmumford@google.com>
Commit-Queue: Darwin Huang <huangdarwin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#651030}
CWE ID: CWE-190
|
static void addArgumentToVtab(Parse *pParse){
if( pParse->sArg.z && pParse->pNewTable ){
const char *z = (const char*)pParse->sArg.z;
int n = pParse->sArg.n;
sqlite3 *db = pParse->db;
addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
}
}
| 173,013
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
panel_(panel) {
const Extension* extension = panel_->GetExtension();
DCHECK(extension);
AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE));
AddItem(COMMAND_UNINSTALL,
l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
AddSeparator();
AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS));
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
panel_(panel) {
const Extension* extension = panel_->GetExtension();
DCHECK(extension);
AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE));
AddItem(COMMAND_UNINSTALL,
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
AddSeparator();
AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS));
}
| 170,983
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const Tracks* Segment::GetTracks() const
{
return m_pTracks;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Tracks* Segment::GetTracks() const
const SegmentInfo* Segment::GetInfo() const { return m_pInfo; }
const Cues* Segment::GetCues() const { return m_pCues; }
const Chapters* Segment::GetChapters() const { return m_pChapters; }
const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; }
long long Segment::GetDuration() const {
assert(m_pInfo);
return m_pInfo->GetDuration();
}
| 174,373
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int LELib_Create(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle) {
ALOGV("LELib_Create()");
int ret;
int i;
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
return -EINVAL;
}
LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;
pContext->mItfe = &gLEInterface;
pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
pContext->mCompressor = NULL;
ret = LE_init(pContext);
if (ret < 0) {
ALOGW("LELib_Create() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV(" LELib_Create context is %p", pContext);
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
|
int LELib_Create(const effect_uuid_t *uuid,
int32_t sessionId __unused,
int32_t ioId __unused,
effect_handle_t *pHandle) {
ALOGV("LELib_Create()");
int ret;
int i;
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
return -EINVAL;
}
LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;
pContext->mItfe = &gLEInterface;
pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
pContext->mCompressor = NULL;
ret = LE_init(pContext);
if (ret < 0) {
ALOGW("LELib_Create() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV(" LELib_Create context is %p", pContext);
return 0;
}
| 173,346
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool PermissionUtil::GetPermissionType(ContentSettingsType type,
PermissionType* out) {
if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
*out = PermissionType::GEOLOCATION;
} else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
*out = PermissionType::NOTIFICATIONS;
} else if (type == CONTENT_SETTINGS_TYPE_PUSH_MESSAGING) {
*out = PermissionType::PUSH_MESSAGING;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
*out = PermissionType::MIDI_SYSEX;
} else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) {
*out = PermissionType::DURABLE_STORAGE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
*out = PermissionType::VIDEO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) {
*out = PermissionType::AUDIO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) {
*out = PermissionType::BACKGROUND_SYNC;
} else if (type == CONTENT_SETTINGS_TYPE_PLUGINS) {
*out = PermissionType::FLASH;
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
} else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) {
*out = PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#endif
} else {
return false;
}
return true;
}
Commit Message: PermissionUtil::GetPermissionType needs to handle MIDI
After the recent PermissionManager's change, it calls
GetPermissionType even for CONTENT_SETTING_TYPE_MIDI.
BUG=697771
Review-Url: https://codereview.chromium.org/2730693002
Cr-Commit-Position: refs/heads/master@{#454231}
CWE ID:
|
bool PermissionUtil::GetPermissionType(ContentSettingsType type,
PermissionType* out) {
if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
*out = PermissionType::GEOLOCATION;
} else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
*out = PermissionType::NOTIFICATIONS;
} else if (type == CONTENT_SETTINGS_TYPE_PUSH_MESSAGING) {
*out = PermissionType::PUSH_MESSAGING;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI) {
*out = PermissionType::MIDI;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
*out = PermissionType::MIDI_SYSEX;
} else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) {
*out = PermissionType::DURABLE_STORAGE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
*out = PermissionType::VIDEO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) {
*out = PermissionType::AUDIO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) {
*out = PermissionType::BACKGROUND_SYNC;
} else if (type == CONTENT_SETTINGS_TYPE_PLUGINS) {
*out = PermissionType::FLASH;
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
} else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) {
*out = PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#endif
} else {
return false;
}
return true;
}
| 172,033
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message:
CWE ID: CWE-310
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| 164,792
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: KeyedService* LogoServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = static_cast<Profile*>(context);
DCHECK(!profile->IsOffTheRecord());
#if defined(OS_ANDROID)
bool use_gray_background = !GetIsChromeHomeEnabled();
#else
bool use_gray_background = false;
#endif
return new LogoService(profile->GetPath().Append(kCachedLogoDirectory),
TemplateURLServiceFactory::GetForProfile(profile),
base::MakeUnique<suggestions::ImageDecoderImpl>(),
profile->GetRequestContext(), use_gray_background);
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <sdefresne@chromium.org>
Reviewed-by: Marc Treib <treib@chromium.org>
Commit-Queue: Chris Pickel <sfiera@chromium.org>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
KeyedService* LogoServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = static_cast<Profile*>(context);
DCHECK(!profile->IsOffTheRecord());
#if defined(OS_ANDROID)
bool use_gray_background = !GetIsChromeHomeEnabled();
#else
bool use_gray_background = false;
#endif
return new LogoServiceImpl(profile->GetPath().Append(kCachedLogoDirectory),
TemplateURLServiceFactory::GetForProfile(profile),
base::MakeUnique<suggestions::ImageDecoderImpl>(),
profile->GetRequestContext(), use_gray_background);
}
| 171,950
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder)
{
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> descriptor;
if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) {
fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
v8::Local<v8::Value> getter;
if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(getter), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) {
rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className);
block.ReThrow();
return v8::Local<v8::Value>();
}
return result;
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79
|
v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder)
{
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> descriptor;
if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) {
fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
v8::Local<v8::Value> getter;
if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(getter), holder, 0, 0, isolate).ToLocal(&result)) {
rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className);
block.ReThrow();
return v8::Local<v8::Value>();
}
return result;
}
| 172,075
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const Block* Track::EOSBlock::GetBlock() const
{
return NULL;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Block* Track::EOSBlock::GetBlock() const
| 174,284
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintPreviewUI::OnReusePreviewData(int preview_request_id) {
base::StringValue ui_identifier(preview_ui_addr_str_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier,
ui_preview_request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewUI::OnReusePreviewData(int preview_request_id) {
base::FundamentalValue ui_identifier(id_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier,
ui_preview_request_id);
}
| 170,840
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: unsigned long long Track::GetDefaultDuration() const
{
return m_info.defaultDuration;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
unsigned long long Track::GetDefaultDuration() const
| 174,302
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void UninstallExtension(ExtensionService* service, const std::string& id) {
if (service && service->GetInstalledExtension(id)) {
service->UninstallExtension(id,
extensions::UNINSTALL_REASON_SYNC,
base::Bind(&base::DoNothing),
NULL);
}
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID:
|
void UninstallExtension(ExtensionService* service, const std::string& id) {
if (service) {
ExtensionService::UninstallExtensionHelper(
service, id, extensions::UNINSTALL_REASON_SYNC);
}
}
| 171,722
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)
{
int ret;
int size;
if (ud->side == USBIP_STUB) {
/* the direction of urb must be OUT. */
if (usb_pipein(urb->pipe))
return 0;
size = urb->transfer_buffer_length;
} else {
/* the direction of urb must be IN. */
if (usb_pipeout(urb->pipe))
return 0;
size = urb->actual_length;
}
/* no need to recv xbuff */
if (!(size > 0))
return 0;
ret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);
if (ret != size) {
dev_err(&urb->dev->dev, "recv xbuf, %d\n", ret);
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
return ret;
}
Commit Message: USB: usbip: fix potential out-of-bounds write
Fix potential out-of-bounds write to urb->transfer_buffer
usbip handles network communication directly in the kernel. When receiving a
packet from its peer, usbip code parses headers according to protocol. As
part of this parsing urb->actual_length is filled. Since the input for
urb->actual_length comes from the network, it should be treated as untrusted.
Any entity controlling the network may put any value in the input and the
preallocated urb->transfer_buffer may not be large enough to hold the data.
Thus, the malicious entity is able to write arbitrary data to kernel memory.
Signed-off-by: Ignat Korchagin <ignat.korchagin@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-119
|
int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)
{
int ret;
int size;
if (ud->side == USBIP_STUB) {
/* the direction of urb must be OUT. */
if (usb_pipein(urb->pipe))
return 0;
size = urb->transfer_buffer_length;
} else {
/* the direction of urb must be IN. */
if (usb_pipeout(urb->pipe))
return 0;
size = urb->actual_length;
}
/* no need to recv xbuff */
if (!(size > 0))
return 0;
if (size > urb->transfer_buffer_length) {
/* should not happen, probably malicious packet */
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
return 0;
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
ret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);
if (ret != size) {
dev_err(&urb->dev->dev, "recv xbuf, %d\n", ret);
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
return ret;
}
| 167,322
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: char *url_decode_r(char *to, char *url, size_t size) {
char *s = url, // source
*d = to, // destination
*e = &to[size - 1]; // destination end
while(*s && d < e) {
if(unlikely(*s == '%')) {
if(likely(s[1] && s[2])) {
*d++ = from_hex(s[1]) << 4 | from_hex(s[2]);
s += 2;
}
}
else if(unlikely(*s == '+'))
*d++ = ' ';
else
*d++ = *s;
s++;
}
*d = '\0';
return to;
}
Commit Message: fixed vulnerabilities identified by red4sec.com (#4521)
CWE ID: CWE-200
|
char *url_decode_r(char *to, char *url, size_t size) {
char *s = url, // source
*d = to, // destination
*e = &to[size - 1]; // destination end
while(*s && d < e) {
if(unlikely(*s == '%')) {
if(likely(s[1] && s[2])) {
char t = from_hex(s[1]) << 4 | from_hex(s[2]);
// avoid HTTP header injection
*d++ = (char)((isprint(t))? t : ' ');
s += 2;
}
}
else if(unlikely(*s == '+'))
*d++ = ' ';
else
*d++ = *s;
s++;
}
*d = '\0';
return to;
}
| 169,812
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int page_index = 0;
if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
url_substr[0], page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int preview_ui_id = -1;
int page_index = 0;
if (url_substr.size() == 3 &&
base::StringToInt(url_substr[0], &preview_ui_id),
base::StringToInt(url_substr[1], &page_index) &&
preview_ui_id >= 0) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
preview_ui_id, page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
| 170,827
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HostCache::Set(const Key& key,
const Entry& entry,
base::TimeTicks now,
base::TimeDelta ttl) {
TRACE_EVENT0(kNetTracingCategory, "HostCache::Set");
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (caching_is_disabled())
return;
auto it = entries_.find(key);
if (it != entries_.end()) {
bool is_stale = it->second.IsStale(now, network_changes_);
RecordSet(is_stale ? SET_UPDATE_STALE : SET_UPDATE_VALID, now, &it->second,
entry);
entries_.erase(it);
} else {
if (size() == max_entries_)
EvictOneEntry(now);
RecordSet(SET_INSERT, now, nullptr, entry);
}
AddEntry(Key(key), Entry(entry, now, ttl, network_changes_));
}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID:
|
void HostCache::Set(const Key& key,
const Entry& entry,
base::TimeTicks now,
base::TimeDelta ttl) {
TRACE_EVENT0(kNetTracingCategory, "HostCache::Set");
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (caching_is_disabled())
return;
bool result_changed = false;
auto it = entries_.find(key);
if (it != entries_.end()) {
bool is_stale = it->second.IsStale(now, network_changes_);
AddressListDeltaType delta =
FindAddressListDeltaType(it->second.addresses(), entry.addresses());
RecordSet(is_stale ? SET_UPDATE_STALE : SET_UPDATE_VALID, now, &it->second,
entry, delta);
result_changed =
entry.error() == OK &&
(it->second.error() != entry.error() || delta != DELTA_IDENTICAL);
entries_.erase(it);
} else {
result_changed = true;
if (size() == max_entries_)
EvictOneEntry(now);
RecordSet(SET_INSERT, now, nullptr, entry, DELTA_DISJOINT);
}
AddEntry(Key(key), Entry(entry, now, ttl, network_changes_));
if (delegate_ && result_changed)
delegate_->ScheduleWrite();
}
| 172,009
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
| 171,422
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DownloadResourceHandler::OnRequestRedirected(
const net::RedirectInfo& redirect_info,
network::ResourceResponse* response,
std::unique_ptr<ResourceController> controller) {
url::Origin new_origin(url::Origin::Create(redirect_info.new_url));
if (!follow_cross_origin_redirects_ &&
!first_origin_.IsSameOriginWith(new_origin)) {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&NavigateOnUIThread, redirect_info.new_url, request()->url_chain(),
Referrer(GURL(redirect_info.new_referrer),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
redirect_info.new_referrer_policy)),
GetRequestInfo()->HasUserGesture(),
GetRequestInfo()->GetWebContentsGetterForRequest()));
controller->Cancel();
return;
}
if (core_.OnRequestRedirected()) {
controller->Resume();
} else {
controller->Cancel();
}
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
|
void DownloadResourceHandler::OnRequestRedirected(
const net::RedirectInfo& redirect_info,
network::ResourceResponse* response,
std::unique_ptr<ResourceController> controller) {
url::Origin new_origin(url::Origin::Create(redirect_info.new_url));
if (!follow_cross_origin_redirects_ &&
!first_origin_.IsSameOriginWith(new_origin)) {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&NavigateOnUIThread, redirect_info.new_url, request()->url_chain(),
Referrer(GURL(redirect_info.new_referrer),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
redirect_info.new_referrer_policy)),
GetRequestInfo()->HasUserGesture(),
GetRequestInfo()->GetWebContentsGetterForRequest(),
GetRequestInfo()->frame_tree_node_id()));
controller->Cancel();
return;
}
if (core_.OnRequestRedirected()) {
controller->Resume();
} else {
controller->Cancel();
}
}
| 173,025
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
Commit Message: Add Android SDK version to crash reports.
Bug: 911669
Change-Id: I62a97d76a0b88099a5a42b93463307f03be9b3e2
Reviewed-on: https://chromium-review.googlesource.com/c/1361104
Reviewed-by: Jochen Eisinger <jochen@chromium.org>
Reviewed-by: Peter Conn <peconn@chromium.org>
Reviewed-by: Ilya Sherman <isherman@chromium.org>
Commit-Queue: Michael van Ouwerkerk <mvanouwerkerk@chromium.org>
Cr-Commit-Position: refs/heads/master@{#615851}
CWE ID: CWE-189
|
void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["sdk"] = base::StringPrintf("%d", info->sdk_int());
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
| 172,546
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SoftAVC::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer =
inHeader->pBuffer + inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20
|
void SoftAVC::setDecodeArgs(
bool SoftAVC::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer =
inHeader->pBuffer + inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,180
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: DataReductionProxySettings::~DataReductionProxySettings() {
spdy_proxy_auth_enabled_.Destroy();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
DataReductionProxySettings::~DataReductionProxySettings() {
| 172,559
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
Commit Message: Remove use of SEE_MASK_FLAG_NO_UI from Chrome Windows installer.
This flag was originally added to ui::base::win to suppress a specific
error message when attempting to open a file via the shell using the
"open" verb. The flag has additional side-effects and shouldn't be used
when invoking ShellExecute().
R=grt@chromium.org
Bug: 819809
Change-Id: I7db2344982dd206c85a73928e906c21e06a47a9e
Reviewed-on: https://chromium-review.googlesource.com/966964
Commit-Queue: Greg Thompson <grt@chromium.org>
Reviewed-by: Greg Thompson <grt@chromium.org>
Cr-Commit-Position: refs/heads/master@{#544012}
CWE ID: CWE-20
|
bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
| 172,793
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
if (params.mailbox_name.length() &&
params.mailbox_name.length() != GL_MAILBOX_SIZE_CHROMIUM)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle,
params.mailbox_name);
}
| 171,358
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserMainParts::PostMainMessageLoopRun() {
CompositorUtils::GetInstance()->Shutdown();
}
Commit Message:
CWE ID: CWE-20
|
void BrowserMainParts::PostMainMessageLoopRun() {
WebContentsUnloader::GetInstance()->Shutdown();
BrowserContextDestroyer::Shutdown();
BrowserContext::AssertNoContextsExist();
CompositorUtils::GetInstance()->Shutdown();
}
| 165,423
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter);
object->u.dir.index = 0;
if (object->u.dir.dirp) {
php_stream_rewinddir(object->u.dir.dirp);
}
spl_filesystem_dir_read(object TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter);
object->u.dir.index = 0;
if (object->u.dir.dirp) {
php_stream_rewinddir(object->u.dir.dirp);
}
spl_filesystem_dir_read(object TSRMLS_CC);
}
| 167,072
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() {
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL;
}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399
|
PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() {
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL;
}
| 171,610
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
FaviconService::Handle handle;
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
handle = favicon_service->GetFaviconForURL(
GURL(path),
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
FaviconService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
GURL url;
if (path.size() > 5 && path.substr(0, 5) == "size/") {
size_t slash = path.find("/", 5);
std::string size = path.substr(5, slash - 5);
int pixel_size = atoi(size.c_str());
CHECK(pixel_size == 32 || pixel_size == 16) <<
"only 32x32 and 16x16 icons are supported";
request_size_map_[request_id] = pixel_size;
url = GURL(path.substr(slash + 1));
} else {
request_size_map_[request_id] = 16;
url = GURL(path);
}
// TODO(estade): fetch the requested size.
handle = favicon_service->GetFaviconForURL(
url,
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
| 170,368
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff32",
"%s", "(cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
| 166,886
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: GesturePoint::GesturePoint()
: first_touch_time_(0.0),
last_touch_time_(0.0),
last_tap_time_(0.0),
velocity_calculator_(kBufferedPoints) {
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
GesturePoint::GesturePoint()
: first_touch_time_(0.0),
last_touch_time_(0.0),
last_tap_time_(0.0),
velocity_calculator_(GestureConfiguration::buffered_points()) {
}
| 171,041
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
const std::string& selection,
const std::string& base_page_url,
int now_on_tap_version)
: version(version),
start(base::string16::npos),
end(base::string16::npos),
selection(selection),
base_page_url(base_page_url),
now_on_tap_version(now_on_tap_version) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
|
TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
const std::string& selection,
const std::string& base_page_url,
int contextual_cards_version)
: version(version),
start(base::string16::npos),
end(base::string16::npos),
selection(selection),
base_page_url(base_page_url),
| 171,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() {
if (render_frame_host_->GetView() &&
render_frame_host_->render_view_host()->GetWidget()->is_hidden() !=
delegate_->IsHidden()) {
if (delegate_->IsHidden()) {
render_frame_host_->GetView()->Hide();
} else {
render_frame_host_->GetView()->Show();
}
}
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
|
void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() {
RenderWidgetHostView* view = GetRenderWidgetHostView();
if (view && static_cast<RenderWidgetHostImpl*>(view->GetRenderWidgetHost())
->is_hidden() != delegate_->IsHidden()) {
if (delegate_->IsHidden()) {
view->Hide();
} else {
view->Show();
}
}
}
| 172,321
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void InputHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (frame_host == host_)
return;
ClearInputState();
if (host_) {
host_->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false);
}
host_ = frame_host;
if (host_) {
host_->GetRenderWidgetHost()->AddInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true);
}
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void InputHandler::SetRenderer(RenderProcessHost* process_host,
void InputHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
if (frame_host == host_)
return;
ClearInputState();
if (host_) {
host_->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false);
}
host_ = frame_host;
if (host_) {
host_->GetRenderWidgetHost()->AddInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true);
}
}
| 172,747
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintPreviewDataService::GetDataEntry(
const std::string& preview_ui_addr_str,
int index,
scoped_refptr<base::RefCountedBytes>* data_bytes) {
*data_bytes = NULL;
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
it->second->GetPreviewDataForIndex(index, data_bytes);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewDataService::GetDataEntry(
int32 preview_ui_id,
int index,
scoped_refptr<base::RefCountedBytes>* data_bytes) {
*data_bytes = NULL;
PreviewDataStoreMap::const_iterator it = data_store_map_.find(preview_ui_id);
if (it != data_store_map_.end())
it->second->GetPreviewDataForIndex(index, data_bytes);
}
| 170,821
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
if (!profile)
return nullptr;
return extensions::InputImeEventRouterFactory::GetInstance()->GetRouter(
profile->GetOriginalProfile());
}
Commit Message: Fix the regression caused by http://crrev.com/c/1288350.
Bug: 900124,856135
Change-Id: Ie11ad406bd1ea383dc2a83cc8661076309154865
Reviewed-on: https://chromium-review.googlesource.com/c/1317010
Reviewed-by: Lan Wei <azurewei@chromium.org>
Commit-Queue: Shu Chen <shuchen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605282}
CWE ID: CWE-416
|
InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
if (!profile)
return nullptr;
return extensions::InputImeEventRouterFactory::GetInstance()->GetRouter(
profile);
}
| 172,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename,
const std::string& mime_type) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
env, filename);
ScopedJavaLocalRef<jstring> jmime_type =
ConvertUTF8ToJavaString(env, mime_type);
Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename,
jmime_type);
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254
|
void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename,
void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
env, filename);
Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename);
}
| 171,879
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: MYSQLND_METHOD(mysqlnd_conn_data, set_server_option)(MYSQLND_CONN_DATA * const conn, enum_mysqlnd_server_option option TSRMLS_DC)
{
size_t this_func = STRUCT_OFFSET(struct st_mysqlnd_conn_data_methods, set_server_option);
zend_uchar buffer[2];
enum_func_status ret = FAIL;
DBG_ENTER("mysqlnd_conn_data::set_server_option");
if (PASS == conn->m->local_tx_start(conn, this_func TSRMLS_CC)) {
int2store(buffer, (unsigned int) option);
ret = conn->m->simple_command(conn, COM_SET_OPTION, buffer, sizeof(buffer), PROT_EOF_PACKET, FALSE, TRUE TSRMLS_CC);
conn->m->local_tx_end(conn, this_func, ret TSRMLS_CC);
}
DBG_RETURN(ret);
}
Commit Message:
CWE ID: CWE-284
|
MYSQLND_METHOD(mysqlnd_conn_data, set_server_option)(MYSQLND_CONN_DATA * const conn, enum_mysqlnd_server_option option TSRMLS_DC)
{
size_t this_func = STRUCT_OFFSET(struct st_mysqlnd_conn_data_methods, set_server_option);
zend_uchar buffer[2];
enum_func_status ret = FAIL;
DBG_ENTER("mysqlnd_conn_data::set_server_option");
if (PASS == conn->m->local_tx_start(conn, this_func TSRMLS_CC)) {
int2store(buffer, (unsigned int) option);
ret = conn->m->simple_command(conn, COM_SET_OPTION, buffer, sizeof(buffer), PROT_EOF_PACKET, FALSE, TRUE TSRMLS_CC);
conn->m->local_tx_end(conn, this_func, ret TSRMLS_CC);
}
DBG_RETURN(ret);
}
| 165,274
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
unsigned int max_num_sg, bool is_write,
hwaddr pa, size_t sz)
{
unsigned num_sg = *p_num_sg;
assert(num_sg <= max_num_sg);
while (sz) {
hwaddr len = sz;
iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
iov[num_sg].iov_len = len;
addr[num_sg] = pa;
sz -= len;
pa += len;
num_sg++;
}
*p_num_sg = num_sg;
}
Commit Message:
CWE ID: CWE-20
|
static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
unsigned int max_num_sg, bool is_write,
hwaddr pa, size_t sz)
{
unsigned num_sg = *p_num_sg;
assert(num_sg <= max_num_sg);
if (!sz) {
error_report("virtio: zero sized buffers are not allowed");
exit(1);
}
while (sz) {
hwaddr len = sz;
iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
iov[num_sg].iov_len = len;
addr[num_sg] = pa;
sz -= len;
pa += len;
num_sg++;
}
*p_num_sg = num_sg;
}
| 164,956
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <jeriko.one@gmx.us>
CWE ID: CWE-77
|
static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name, true);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
| 169,134
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_emit_signal2 (MyObject *obj, GError **error)
{
GHashTable *table;
table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (table, "baz", "cow");
g_hash_table_insert (table, "bar", "foo");
g_signal_emit (obj, signals[SIG2], 0, table);
g_hash_table_destroy (table);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_emit_signal2 (MyObject *obj, GError **error)
| 165,095
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void ext4_free_io_end(ext4_io_end_t *io)
{
BUG_ON(!io);
iput(io->inode);
kfree(io);
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_free_io_end(ext4_io_end_t *io)
| 167,544
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
Commit Message:
CWE ID:
|
hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->in_error = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
| 164,772
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserPluginGuest::SetCompositingBufferData(int gpu_process_id,
uint32 client_id,
uint32 context_id,
uint32 texture_id_0,
uint32 texture_id_1,
uint32 sync_point) {
if (texture_id_0 == 0) {
DCHECK(texture_id_1 == 0);
return;
}
DCHECK(texture_id_1 != 0);
DCHECK(texture_id_0 != texture_id_1);
surface_handle_ = gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true);
surface_handle_.parent_gpu_process_id = gpu_process_id;
surface_handle_.parent_client_id = client_id;
surface_handle_.parent_context_id = context_id;
surface_handle_.parent_texture_id[0] = texture_id_0;
surface_handle_.parent_texture_id[1] = texture_id_1;
surface_handle_.sync_point = sync_point;
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BrowserPluginGuest::SetCompositingBufferData(int gpu_process_id,
uint32 client_id,
uint32 context_id,
uint32 texture_id_0,
uint32 texture_id_1,
uint32 sync_point) {
if (texture_id_0 == 0) {
DCHECK(texture_id_1 == 0);
return;
}
DCHECK(texture_id_1 != 0);
DCHECK(texture_id_0 != texture_id_1);
surface_handle_ = gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true);
surface_handle_.parent_gpu_process_id = gpu_process_id;
surface_handle_.parent_client_id = client_id;
}
| 171,352
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) {
if (ComputeVisibleSelectionInDOMTree().IsNone())
return;
SetSelection(
SelectionInDOMTree::Builder(
GetGranularityStrategy()->UpdateExtent(contents_point, frame_))
.SetIsHandleVisible(true)
.Build(),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotClearStrategy(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.Build());
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <yosin@chromium.org>
Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org>
Reviewed-by: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
|
void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) {
if (ComputeVisibleSelectionInDOMTree().IsNone())
return;
SetSelection(
SelectionInDOMTree::Builder(
GetGranularityStrategy()->UpdateExtent(contents_point, frame_))
.Build(),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotClearStrategy(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.SetShouldShowHandle(true)
.Build());
}
| 171,758
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool HeapAllocator::backingExpand(void* address, size_t newSize) {
if (!address)
return false;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return false;
ASSERT(!state->isInGC());
ASSERT(state->isAllocationAllowed());
DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return false;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
ASSERT(header->checkHeader());
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
bool succeed = arena->expandObject(header, newSize);
if (succeed)
state->allocationPointAdjusted(arena->arenaIndex());
return succeed;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119
|
bool HeapAllocator::backingExpand(void* address, size_t newSize) {
if (!address)
return false;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return false;
ASSERT(!state->isInGC());
ASSERT(state->isAllocationAllowed());
DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return false;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
header->checkHeader();
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
bool succeed = arena->expandObject(header, newSize);
if (succeed)
state->allocationPointAdjusted(arena->arenaIndex());
return succeed;
}
| 172,705
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg)
{
struct flakey_c *fc = ti->private;
return __blkdev_driver_ioctl(fc->dev->bdev, fc->dev->mode, cmd, arg);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <agk@redhat.com>
Cc: dm-devel@redhat.com
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264
|
static int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg)
{
struct flakey_c *fc = ti->private;
struct dm_dev *dev = fc->dev;
int r = 0;
/*
* Only pass ioctls through if the device sizes match exactly.
*/
if (fc->start ||
ti->len != i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT)
r = scsi_verify_blk_ioctl(NULL, cmd);
return r ? : __blkdev_driver_ioctl(dev->bdev, dev->mode, cmd, arg);
}
| 165,722
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
{
struct session_state *state = ssh->state;
struct sshbuf *b;
int r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if (state->compression_in_started) {
if ((r = sshbuf_put_string(b, &state->compression_in_stream,
sizeof(state->compression_in_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
if (state->compression_out_started) {
if ((r = sshbuf_put_string(b, &state->compression_out_stream,
sizeof(state->compression_out_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
| 168,652
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[1024];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
sprintf (pathName, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
Commit Message:
CWE ID: CWE-119
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
| 164,654
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AsyncPixelTransfersCompletedQuery::End(
base::subtle::Atomic32 submit_count) {
AsyncMemoryParams mem_params;
Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id());
if (!buffer.shared_memory)
return false;
mem_params.shared_memory = buffer.shared_memory;
mem_params.shm_size = buffer.size;
mem_params.shm_data_offset = shm_offset();
mem_params.shm_data_size = sizeof(QuerySync);
observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count);
manager()->decoder()->GetAsyncPixelTransferManager()
->AsyncNotifyCompletion(mem_params, observer_);
return AddToPendingTransferQueue(submit_count);
}
Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End
BUG=351852
R=jbauman@chromium.org, jorgelo@chromium.org
Review URL: https://codereview.chromium.org/198253002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
bool AsyncPixelTransfersCompletedQuery::End(
base::subtle::Atomic32 submit_count) {
AsyncMemoryParams mem_params;
Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id());
if (!buffer.shared_memory)
return false;
mem_params.shared_memory = buffer.shared_memory;
mem_params.shm_size = buffer.size;
mem_params.shm_data_offset = shm_offset();
mem_params.shm_data_size = sizeof(QuerySync);
uint32 end = mem_params.shm_data_offset + mem_params.shm_data_size;
if (end > mem_params.shm_size || end < mem_params.shm_data_offset)
return false;
observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count);
manager()->decoder()->GetAsyncPixelTransferManager()
->AsyncNotifyCompletion(mem_params, observer_);
return AddToPendingTransferQueue(submit_count);
}
| 171,682
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct hrtimer *timer;
if (!kvm_vcpu_is_bsp(vcpu) || !pit)
return;
timer = &pit->pit_state.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
Commit Message: KVM: x86: Improve thread safety in pit
There's a race condition in the PIT emulation code in KVM. In
__kvm_migrate_pit_timer the pit_timer object is accessed without
synchronization. If the race condition occurs at the wrong time this
can crash the host kernel.
This fixes CVE-2014-3611.
Cc: stable@vger.kernel.org
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-362
|
void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct hrtimer *timer;
if (!kvm_vcpu_is_bsp(vcpu) || !pit)
return;
timer = &pit->pit_state.timer;
mutex_lock(&pit->pit_state.lock);
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
mutex_unlock(&pit->pit_state.lock);
}
| 166,347
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_generic)
{
zval *mcryptind;
char *data;
int data_len;
php_mcrypt *pm;
unsigned char* data_s;
int block_size, data_size;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
PHP_MCRYPT_INIT_CHECK
if (data_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed");
RETURN_FALSE
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(pm->td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
mcrypt_generic(pm->td, data_s, data_size);
data_s[data_size] = '\0';
RETVAL_STRINGL(data_s, data_size, 1);
efree(data_s);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_generic)
{
zval *mcryptind;
char *data;
int data_len;
php_mcrypt *pm;
unsigned char* data_s;
int block_size, data_size;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
PHP_MCRYPT_INIT_CHECK
if (data_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed");
RETURN_FALSE
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(pm->td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
if (data_size <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Integer overflow in data size");
RETURN_FALSE;
}
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
mcrypt_generic(pm->td, data_s, data_size);
data_s[data_size] = '\0';
RETVAL_STRINGL(data_s, data_size, 1);
efree(data_s);
}
| 167,091
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
std::string* error) {
int error_code = 0;
Value* params =
base::JSONReader::ReadAndReturnError(json, true, &error_code, error);
if (error_code != 0) {
VLOG(1) << "Could not parse JSON object, " << *error;
if (params)
delete params;
return false;
}
if (!params || params->GetType() != Value::TYPE_DICTIONARY) {
*error = "Data passed in URL must be of type dictionary.";
VLOG(1) << "Invalid type to parse";
if (params)
delete params;
return false;
}
*dict = static_cast<DictionaryValue*>(params);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
| 170,466
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
| 171,689
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RegisterProperties(IBusPropList* ibus_prop_list) {
DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
RegisterProperties(NULL);
return;
}
}
register_ime_properties_(language_library_, prop_list);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void RegisterProperties(IBusPropList* ibus_prop_list) {
void DoRegisterProperties(IBusPropList* ibus_prop_list) {
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
DoRegisterProperties(NULL);
return;
}
}
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
| 170,544
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
| 172,787
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_scale_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
| 173,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SendStatus(struct mg_connection* connection,
const struct mg_request_info* request_info,
void* user_data) {
std::string response = "HTTP/1.1 200 OK\r\n"
"Content-Length:2\r\n\r\n"
"ok";
mg_write(connection, response.data(), response.length());
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void SendStatus(struct mg_connection* connection,
void SendOkWithBody(struct mg_connection* connection,
const std::string& content) {
const char* response_fmt = "HTTP/1.1 200 OK\r\n"
"Content-Length:%d\r\n\r\n"
"%s";
std::string response = base::StringPrintf(
response_fmt, content.length(), content.c_str());
mg_write(connection, response.data(), response.length());
}
| 170,458
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AppModalDialog::CompleteDialog() {
AppModalDialogQueue::GetInstance()->ShowNextDialog();
}
Commit Message: Fix a Windows crash bug with javascript alerts from extension popups.
BUG=137707
Review URL: https://chromiumcodereview.appspot.com/10828423
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void AppModalDialog::CompleteDialog() {
if (!completed_) {
completed_ = true;
AppModalDialogQueue::GetInstance()->ShowNextDialog();
}
}
| 170,754
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_throw_error (MyObject *obj, GError **error)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"this method always loses");
return FALSE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_throw_error (MyObject *obj, GError **error)
| 165,124
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
| 174,521
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline int mk_vhost_fdt_close(struct session_request *sr)
{
int id;
unsigned int hash;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return close(sr->fd_file);
}
id = sr->vhost_fdt_id;
hash = sr->vhost_fdt_hash;
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return close(sr->fd_file);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and check if we should close */
hc->readers--;
if (hc->readers == 0) {
hc->fd = -1;
hc->hash = 0;
ht->av_slots++;
return close(sr->fd_file);
}
else {
return 0;
}
}
return close(sr->fd_file);
}
Commit Message: Request: new request session flag to mark those files opened by FDT
This patch aims to fix a potential DDoS problem that can be caused
in the server quering repetitive non-existent resources.
When serving a static file, the core use Vhost FDT mechanism, but if
it sends a static error page it does a direct open(2). When closing
the resources for the same request it was just calling mk_vhost_close()
which did not clear properly the file descriptor.
This patch adds a new field on the struct session_request called 'fd_is_fdt',
which contains MK_TRUE or MK_FALSE depending of how fd_file was opened.
Thanks to Matthew Daley <mattd@bugfuzz.com> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <eduardo@monkey.io>
CWE ID: CWE-20
|
static inline int mk_vhost_fdt_close(struct session_request *sr)
{
int id;
unsigned int hash;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return close(sr->fd_file);
}
id = sr->vhost_fdt_id;
hash = sr->vhost_fdt_hash;
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return close(sr->fd_file);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and check if we should close */
hc->readers--;
if (hc->readers == 0) {
hc->fd = -1;
hc->hash = 0;
ht->av_slots++;
return close(sr->fd_file);
}
else {
return 0;
}
}
return close(sr->fd_file);
}
| 166,278
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
|
static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
| 167,180
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
{
uint32_t old_val;
trace_esp_mem_readb(saddr, s->rregs[saddr]);
switch (saddr) {
case ESP_FIFO:
if (s->ti_size > 0) {
s->ti_size--;
if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
/* Data out. */
qemu_log_mask(LOG_UNIMP,
"esp: PIO data read not implemented\n");
s->rregs[ESP_FIFO] = 0;
} else {
s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
}
esp_raise_irq(s);
}
if (s->ti_size == 0) {
s->ti_rptr = 0;
s->ti_wptr = 0;
}
s->ti_wptr = 0;
}
break;
case ESP_RINTR:
/* Clear sequence step, interrupt register and all status bits
except TC */
old_val = s->rregs[ESP_RINTR];
s->rregs[ESP_RINTR] = 0;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
esp_lower_irq(s);
return old_val;
case ESP_TCHI:
/* Return the unique id if the value has never been written */
if (!s->tchi_written) {
return s->chip_id;
}
default:
break;
}
Commit Message:
CWE ID: CWE-20
|
uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
{
uint32_t old_val;
trace_esp_mem_readb(saddr, s->rregs[saddr]);
switch (saddr) {
case ESP_FIFO:
if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
/* Data out. */
qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n");
s->rregs[ESP_FIFO] = 0;
esp_raise_irq(s);
} else if (s->ti_rptr < s->ti_wptr) {
s->ti_size--;
s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
esp_raise_irq(s);
}
if (s->ti_rptr == s->ti_wptr) {
s->ti_rptr = 0;
s->ti_wptr = 0;
}
s->ti_wptr = 0;
}
break;
case ESP_RINTR:
/* Clear sequence step, interrupt register and all status bits
except TC */
old_val = s->rregs[ESP_RINTR];
s->rregs[ESP_RINTR] = 0;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
esp_lower_irq(s);
return old_val;
case ESP_TCHI:
/* Return the unique id if the value has never been written */
if (!s->tchi_written) {
return s->chip_id;
}
default:
break;
}
| 165,012
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.