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: static inline int btif_hl_select_wakeup(void){
char sig_on = btif_hl_signal_select_wakeup;
BTIF_TRACE_DEBUG("btif_hl_select_wakeup");
return send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
}
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
|
static inline int btif_hl_select_wakeup(void){
char sig_on = btif_hl_signal_select_wakeup;
BTIF_TRACE_DEBUG("btif_hl_select_wakeup");
return TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0));
}
| 173,444
|
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 NetworkHandler::ClearBrowserCookies(
std::unique_ptr<ClearBrowserCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&ClearCookiesOnIO,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
std::move(callback)));
}
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 NetworkHandler::ClearBrowserCookies(
std::unique_ptr<ClearBrowserCookiesCallback> callback) {
if (!storage_partition_) {
callback->sendFailure(Response::InternalError());
return;
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&ClearCookiesOnIO,
base::Unretained(storage_partition_->GetURLRequestContext()),
std::move(callback)));
}
| 172,753
|
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: PluginModule::PluginModule(const std::string& name,
const FilePath& path,
PluginDelegate::ModuleLifetime* lifetime_delegate)
: lifetime_delegate_(lifetime_delegate),
callback_tracker_(new ::ppapi::CallbackTracker),
is_in_destructor_(false),
is_crashed_(false),
broker_(NULL),
library_(NULL),
name_(name),
path_(path),
reserve_instance_id_(NULL),
nacl_ipc_proxy_(false) {
if (!host_globals)
host_globals = new HostGlobals;
memset(&entry_points_, 0, sizeof(entry_points_));
pp_module_ = HostGlobals::Get()->AddModule(this);
GetMainThreadMessageLoop(); // Initialize the main thread message loop.
GetLivePluginSet()->insert(this);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
PluginModule::PluginModule(const std::string& name,
const FilePath& path,
PluginDelegate::ModuleLifetime* lifetime_delegate)
: lifetime_delegate_(lifetime_delegate),
callback_tracker_(new ::ppapi::CallbackTracker),
is_in_destructor_(false),
is_crashed_(false),
broker_(NULL),
library_(NULL),
name_(name),
path_(path),
reserve_instance_id_(NULL) {
if (!host_globals)
host_globals = new HostGlobals;
memset(&entry_points_, 0, sizeof(entry_points_));
pp_module_ = HostGlobals::Get()->AddModule(this);
GetMainThreadMessageLoop(); // Initialize the main thread message loop.
GetLivePluginSet()->insert(this);
}
| 170,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: static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
{
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = kiocb->ki_left;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <manish_honap_vit@yahoo.co.in>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID:
|
static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
static ssize_t aio_setup_single_vector(int type, struct file * file, struct kiocb *kiocb)
{
int bytes;
bytes = rw_verify_area(type, file, &kiocb->ki_pos, kiocb->ki_left);
if (bytes < 0)
return bytes;
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = bytes;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
| 167,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: TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
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
|
TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage", "test",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
| 172,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: static void on_read(h2o_socket_t *sock, int status)
{
h2o_http2_conn_t *conn = sock->data;
if (status != 0) {
h2o_socket_read_stop(conn->sock);
close_connection(conn);
return;
}
update_idle_timeout(conn);
parse_input(conn);
/* write immediately, if there is no write in flight and if pending write exists */
if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) {
h2o_timeout_unlink(&conn->_write.timeout_entry);
do_emit_writereq(conn);
}
}
Commit Message: h2: use after free on premature connection close #920
lib/http2/connection.c:on_read() calls parse_input(), which might free
`conn`. It does so in particular if the connection preface isn't
the expected one in expect_preface(). `conn` is then used after the free
in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`.
We fix this by adding a return value to close_connection that returns a
negative value if `conn` has been free'd and can't be used anymore.
Credits for finding the bug to Tim Newsham.
CWE ID:
|
static void on_read(h2o_socket_t *sock, int status)
{
h2o_http2_conn_t *conn = sock->data;
if (status != 0) {
h2o_socket_read_stop(conn->sock);
close_connection(conn);
return;
}
update_idle_timeout(conn);
if (parse_input(conn) != 0)
return;
/* write immediately, if there is no write in flight and if pending write exists */
if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) {
h2o_timeout_unlink(&conn->_write.timeout_entry);
do_emit_writereq(conn);
}
}
| 167,226
|
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 BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
}
Commit Message: Fixed CVE-2018-8784
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119
|
static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
return TRUE;
}
| 169,296
|
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 DownloadController::StartAndroidDownloadInternal(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info, bool allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!allowed)
return;
WebContents* web_contents = wc_getter.Run();
if (!web_contents)
return;
base::string16 filename = net::GetSuggestedFilename(
info.url, info.content_disposition,
std::string(), // referrer_charset
std::string(), // suggested_name
info.original_mime_type,
default_file_name_);
ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload(
info.url.spec(), info.user_agent,
info.content_disposition, info.original_mime_type,
info.cookie, info.referer, filename,
info.total_bytes, info.has_user_gesture,
must_download);
}
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 DownloadController::StartAndroidDownloadInternal(
| 171,884
|
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: DevToolsUI::DevToolsUI(content::WebUI* web_ui)
: WebUIController(web_ui),
bindings_(web_ui->GetWebContents()) {
web_ui->SetBindings(0);
Profile* profile = Profile::FromWebUI(web_ui);
content::URLDataSource::Add(
profile,
new DevToolsDataSource(profile->GetRequestContext()));
}
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
CWE ID: CWE-200
|
DevToolsUI::DevToolsUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
web_ui->SetBindings(0);
Profile* profile = Profile::FromWebUI(web_ui);
content::URLDataSource::Add(
profile,
new DevToolsDataSource(profile->GetRequestContext()));
GURL url = web_ui->GetWebContents()->GetVisibleURL();
if (url.spec() == SanitizeFrontendURL(url).spec())
bindings_.reset(new DevToolsUIBindings(web_ui->GetWebContents()));
}
| 172,510
|
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 AXObject::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringCase(getAttribute(aria_multilineAttr), "true");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXObject::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringASCIICase(getAttribute(aria_multilineAttr), "true");
}
| 171,928
|
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 mark_files_ro(struct super_block *sb)
{
struct file *f;
lg_global_lock(&files_lglock);
do_file_list_for_each_entry(sb, f) {
if (!file_count(f))
continue;
if (!(f->f_mode & FMODE_WRITE))
continue;
spin_lock(&f->f_lock);
f->f_mode &= ~FMODE_WRITE;
spin_unlock(&f->f_lock);
if (file_check_writeable(f) != 0)
continue;
__mnt_drop_write(f->f_path.mnt);
file_release_write(f);
} while_file_list_for_each_entry;
lg_global_unlock(&files_lglock);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
|
void mark_files_ro(struct super_block *sb)
| 166,803
|
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 BluetoothDeviceChromeOS::RejectPairing() {
RunPairingCallbacks(REJECTED);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::RejectPairing() {
if (!pairing_context_.get())
return;
pairing_context_->RejectPairing();
}
| 171,232
|
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::Frame& Block::GetFrame(int idx) const
{
assert(idx >= 0);
assert(idx < m_frame_count);
const Frame& f = m_frames[idx];
assert(f.pos > 0);
assert(f.len > 0);
return f;
}
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::Frame& Block::GetFrame(int idx) const
| 174,324
|
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 sk_sp<SkImage> scaleSkImage(sk_sp<SkImage> skImage,
unsigned resizeWidth,
unsigned resizeHeight,
SkFilterQuality resizeQuality) {
SkImageInfo resizedInfo = SkImageInfo::Make(
resizeWidth, resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType);
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
resizeWidth * resizeHeight, resizedInfo.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> resizedPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
SkPixmap pixmap(
resizedInfo, resizedPixels->data(),
static_cast<size_t>(resizeWidth) * resizedInfo.bytesPerPixel());
skImage->scalePixels(pixmap, resizeQuality);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
resizedPixels.release().leakRef());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
|
static sk_sp<SkImage> scaleSkImage(sk_sp<SkImage> skImage,
unsigned resizeWidth,
unsigned resizeHeight,
SkFilterQuality resizeQuality) {
SkImageInfo resizedInfo = SkImageInfo::Make(
resizeWidth, resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType);
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
resizeWidth * resizeHeight, resizedInfo.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> resizedPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
SkPixmap pixmap(
resizedInfo, resizedPixels->data(),
static_cast<unsigned>(resizeWidth) * resizedInfo.bytesPerPixel());
skImage->scalePixels(pixmap, resizeQuality);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
resizedPixels.release().leakRef());
}
| 172,505
|
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: double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
uint32_t key, insamples;
uint32_t repeat, outsamples;
GPMF_stream find_stream;
if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;
key = GPMF_Key(gs);
repeat = GPMF_Repeat(gs);
if (rate == 0.0)
rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);
if (rate == 0.0)
{
*in = *out = 0.0;
return 0.0;
}
GPMF_CopyState(gs, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
insamples = outsamples - repeat;
*in = ((double)insamples / (double)rate);
*out = ((double)outsamples / (double)rate);
}
else
{
*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
}
return rate;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787
|
double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL))
GPMF_FormattedData(&find_stream, &timo, 4, 0, 1);
double first, last;
first = -intercept / rate - timo;
last = first + (double)totalsamples / rate;
//printf("%c%c%c%c first sample at time %.3fms, last at %.3fms\n", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last);
if (firstsampletime) *firstsampletime = first;
if (lastsampletime) *lastsampletime = last;
}
}
}
}
cleanup:
if (payload)
FreePayload(payload);
payload = NULL;
return rate;
}
| 169,547
|
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 readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint16 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
Commit Message: * tools/tiffcp.c: fix read of undefined variable in case of missing
required tags. Found on test case of MSVR 35100.
* tools/tiffcrop.c: fix read of undefined buffer in
readContigStripsIntoBuffer() due to uint16 overflow. Probably not a
security issue but I can be wrong. Reported as MSVR 35100 by Axel
Souchet from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-190
|
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
| 166,866
|
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 ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = mrt->mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = mrt->mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <lucien.xin@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
|
int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = mrt->mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = mrt->mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
| 169,857
|
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_NAMED_FUNCTION(zif_locale_set_default)
{
char* locale_name = NULL;
int len=0;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&locale_name ,&len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_set_default: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(len == 0) {
locale_name = (char *)uloc_getDefault() ;
len = strlen(locale_name);
}
zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
RETURN_TRUE;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_NAMED_FUNCTION(zif_locale_set_default)
{
char* locale_name = NULL;
int len=0;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&locale_name ,&len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_set_default: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(len == 0) {
locale_name = (char *)uloc_getDefault() ;
len = strlen(locale_name);
}
zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
RETURN_TRUE;
}
| 167,196
|
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::SetPrintPreviewDataForIndex(
int index,
const base::RefCountedBytes* data) {
print_preview_data_service()->SetDataEntry(preview_ui_addr_str_, index, 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 PrintPreviewUI::SetPrintPreviewDataForIndex(
int index,
const base::RefCountedBytes* data) {
print_preview_data_service()->SetDataEntry(id_, index, data);
}
| 170,843
|
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 SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) {
int dummy;
Bool pixmaps_supported;
if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported))
return SHARED_MEMORY_NONE;
#if defined(OS_FREEBSD)
int allow_removed;
size_t length = sizeof(allow_removed);
if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length,
NULL, 0) < 0) || allow_removed < 1) {
return SHARED_MEMORY_NONE;
}
#endif
int shmkey = shmget(IPC_PRIVATE, 1, 0666);
if (shmkey == -1)
return SHARED_MEMORY_NONE;
void* address = shmat(shmkey, NULL, 0);
shmctl(shmkey, IPC_RMID, NULL);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shmkey;
gdk_error_trap_push();
bool result = XShmAttach(dpy, &shminfo);
XSync(dpy, False);
if (gdk_error_trap_pop())
result = false;
shmdt(address);
if (!result)
return SHARED_MEMORY_NONE;
XShmDetach(dpy, &shminfo);
return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
static SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) {
int dummy;
Bool pixmaps_supported;
if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported))
return SHARED_MEMORY_NONE;
#if defined(OS_FREEBSD)
int allow_removed;
size_t length = sizeof(allow_removed);
if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length,
NULL, 0) < 0) || allow_removed < 1) {
return SHARED_MEMORY_NONE;
}
#endif
int shmkey = shmget(IPC_PRIVATE, 1, 0600);
if (shmkey == -1) {
LOG(WARNING) << "Failed to get shared memory segment.";
return SHARED_MEMORY_NONE;
} else {
VLOG(1) << "Got shared memory segment " << shmkey;
}
void* address = shmat(shmkey, NULL, 0);
shmctl(shmkey, IPC_RMID, NULL);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shmkey;
gdk_error_trap_push();
bool result = XShmAttach(dpy, &shminfo);
if (result)
VLOG(1) << "X got shared memory segment " << shmkey;
else
LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey;
XSync(dpy, False);
if (gdk_error_trap_pop())
result = false;
shmdt(address);
if (!result) {
LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey;
return SHARED_MEMORY_NONE;
}
VLOG(1) << "X attached to shared memory segment " << shmkey;
XShmDetach(dpy, &shminfo);
return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE;
}
| 171,594
|
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: struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt)
{
struct svc_rdma_req_map *map = NULL;
spin_lock(&xprt->sc_map_lock);
if (list_empty(&xprt->sc_maps))
goto out_empty;
map = list_first_entry(&xprt->sc_maps,
struct svc_rdma_req_map, free);
list_del_init(&map->free);
spin_unlock(&xprt->sc_map_lock);
out:
map->count = 0;
return map;
out_empty:
spin_unlock(&xprt->sc_map_lock);
/* Pre-allocation amount was incorrect */
map = alloc_req_map(GFP_NOIO);
if (map)
goto out;
WARN_ONCE(1, "svcrdma: empty request map list?\n");
return NULL;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt)
| 168,181
|
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 *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = poll(pfds, 1, 50);
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
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
|
static void *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = TEMP_FAILURE_RETRY(poll(pfds, 1, 50));
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
| 173,431
|
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 rose_parse_facilities(unsigned char *p,
struct rose_facilities_struct *facilities)
{
int facilities_len, len;
facilities_len = *p++;
if (facilities_len == 0)
return 0;
while (facilities_len > 0) {
if (*p == 0x00) {
facilities_len--;
p++;
switch (*p) {
case FAC_NATIONAL: /* National */
len = rose_parse_national(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
case FAC_CCITT: /* CCITT */
len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
default:
printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p);
facilities_len--;
p++;
break;
}
} else
break; /* Error in facilities format */
}
return 1;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: stable@kernel.org
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
|
int rose_parse_facilities(unsigned char *p,
struct rose_facilities_struct *facilities)
{
int facilities_len, len;
facilities_len = *p++;
if (facilities_len == 0)
return 0;
while (facilities_len > 0) {
if (*p == 0x00) {
facilities_len--;
p++;
switch (*p) {
case FAC_NATIONAL: /* National */
len = rose_parse_national(p + 1, facilities, facilities_len - 1);
if (len < 0)
return 0;
facilities_len -= len + 1;
p += len + 1;
break;
case FAC_CCITT: /* CCITT */
len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);
if (len < 0)
return 0;
facilities_len -= len + 1;
p += len + 1;
break;
default:
printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p);
facilities_len--;
p++;
break;
}
} else
break; /* Error in facilities format */
}
return 1;
}
| 165,672
|
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: DefragIPv4NoDataTest(void)
{
DefragContext *dc = NULL;
Packet *p = NULL;
int id = 12;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
/* This packet has an offset > 0, more frags set to 0 and no data. */
p = BuildTestPacket(id, 1, 0, 'A', 0);
if (p == NULL)
goto end;
/* We do not expect a packet returned. */
if (Defrag(NULL, NULL, p, NULL) != NULL)
goto end;
/* The fragment should have been ignored so no fragments should
* have been allocated from the pool. */
if (dc->frag_pool->outstanding != 0)
return 0;
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p != NULL)
SCFree(p);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358
|
DefragIPv4NoDataTest(void)
{
DefragContext *dc = NULL;
Packet *p = NULL;
int id = 12;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
/* This packet has an offset > 0, more frags set to 0 and no data. */
p = BuildTestPacket(IPPROTO_ICMP, id, 1, 0, 'A', 0);
if (p == NULL)
goto end;
/* We do not expect a packet returned. */
if (Defrag(NULL, NULL, p, NULL) != NULL)
goto end;
/* The fragment should have been ignored so no fragments should
* have been allocated from the pool. */
if (dc->frag_pool->outstanding != 0)
return 0;
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p != NULL)
SCFree(p);
DefragDestroy();
return ret;
}
| 168,296
|
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 EncoderTest::MismatchHook(const vpx_image_t *img1,
const vpx_image_t *img2) {
ASSERT_TRUE(0) << "Encode/Decode mismatch found";
}
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 EncoderTest::MismatchHook(const vpx_image_t *img1,
void EncoderTest::MismatchHook(const vpx_image_t* /*img1*/,
const vpx_image_t* /*img2*/) {
ASSERT_TRUE(0) << "Encode/Decode mismatch found";
}
| 174,539
|
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 WorkerProcessLauncherTest::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid())
return false;
channel_name_ = GenerateIpcChannelName(this);
if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, task_runner_,
delegate, &channel_server_)) {
return false;
}
exit_code_ = STILL_ACTIVE;
return DuplicateHandle(GetCurrentProcess(),
process_exit_event_,
GetCurrentProcess(),
process_exit_event_out->Receive(),
0,
FALSE,
DUPLICATE_SAME_ACCESS) != FALSE;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool WorkerProcessLauncherTest::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid())
return false;
channel_name_ = GenerateIpcChannelName(this);
ScopedHandle pipe;
if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, &pipe)) {
return false;
}
// Wrap the pipe into an IPC channel.
channel_server_.reset(new IPC::ChannelProxy(
IPC::ChannelHandle(pipe),
IPC::Channel::MODE_SERVER,
delegate,
task_runner_));
return DuplicateHandle(GetCurrentProcess(),
process_exit_event_,
GetCurrentProcess(),
process_exit_event_out->Receive(),
0,
FALSE,
DUPLICATE_SAME_ACCESS) != FALSE;
}
| 171,551
|
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 ssd0323_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssd0323_state *s = (ssd0323_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->cmd_len = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 8; i++)
s->cmd_data[i] = qemu_get_be32(f);
s->row = qemu_get_be32(f);
s->row_start = qemu_get_be32(f);
s->row_end = qemu_get_be32(f);
s->col = qemu_get_be32(f);
s->col_start = qemu_get_be32(f);
s->col_end = qemu_get_be32(f);
s->redraw = qemu_get_be32(f);
s->remap = qemu_get_be32(f);
s->mode = qemu_get_be32(f);
qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer));
ss->cs = qemu_get_be32(f);
}
Commit Message:
CWE ID: CWE-119
|
static int ssd0323_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssd0323_state *s = (ssd0323_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->cmd_len = qemu_get_be32(f);
if (s->cmd_len < 0 || s->cmd_len > ARRAY_SIZE(s->cmd_data)) {
return -EINVAL;
}
s->cmd = qemu_get_be32(f);
for (i = 0; i < 8; i++)
s->cmd_data[i] = qemu_get_be32(f);
s->row = qemu_get_be32(f);
if (s->row < 0 || s->row >= 80) {
return -EINVAL;
}
s->row_start = qemu_get_be32(f);
if (s->row_start < 0 || s->row_start >= 80) {
return -EINVAL;
}
s->row_end = qemu_get_be32(f);
if (s->row_end < 0 || s->row_end >= 80) {
return -EINVAL;
}
s->col = qemu_get_be32(f);
if (s->col < 0 || s->col >= 64) {
return -EINVAL;
}
s->col_start = qemu_get_be32(f);
if (s->col_start < 0 || s->col_start >= 64) {
return -EINVAL;
}
s->col_end = qemu_get_be32(f);
if (s->col_end < 0 || s->col_end >= 64) {
return -EINVAL;
}
s->redraw = qemu_get_be32(f);
s->remap = qemu_get_be32(f);
s->mode = qemu_get_be32(f);
if (s->mode != SSD0323_CMD && s->mode != SSD0323_DATA) {
return -EINVAL;
}
qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer));
ss->cs = qemu_get_be32(f);
}
| 165,357
|
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: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125
|
juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
ND_TCHECK2(p[0], 3);
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_atm2]"));
return l2info.header_len;
}
| 167,915
|
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: freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
(void)remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
| 173,594
|
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 WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
pipe_.Close();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
| 171,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: void exit_io_context(void)
{
struct io_context *ioc;
task_lock(current);
ioc = current->io_context;
current->io_context = NULL;
task_unlock(current);
if (atomic_dec_and_test(&ioc->nr_tasks)) {
if (ioc->aic && ioc->aic->exit)
ioc->aic->exit(ioc->aic);
cfq_exit(ioc);
}
put_io_context(ioc);
}
Commit Message: block: Fix io_context leak after failure of clone with CLONE_IO
With CLONE_IO, parent's io_context->nr_tasks is incremented, but never
decremented whenever copy_process() fails afterwards, which prevents
exit_io_context() from calling IO schedulers exit functions.
Give a task_struct to exit_io_context(), and call exit_io_context() instead of
put_io_context() in copy_process() cleanup path.
Signed-off-by: Louis Rilling <louis.rilling@kerlabs.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
CWE ID: CWE-20
|
void exit_io_context(void)
void exit_io_context(struct task_struct *task)
{
struct io_context *ioc;
task_lock(task);
ioc = task->io_context;
task->io_context = NULL;
task_unlock(task);
if (atomic_dec_and_test(&ioc->nr_tasks)) {
if (ioc->aic && ioc->aic->exit)
ioc->aic->exit(ioc->aic);
cfq_exit(ioc);
}
put_io_context(ioc);
}
| 169,885
|
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 sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
size_t width = static_cast<size_t>(input->width());
size_t height = static_cast<size_t>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
size_t imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (size_t i = 0; i < height / 2; i++) {
size_t topFirstElement = i * imageRowBytes;
size_t topLastElement = (i + 1) * imageRowBytes;
size_t bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
|
static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
unsigned width = static_cast<unsigned>(input->width());
unsigned height = static_cast<unsigned>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
unsigned imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (unsigned i = 0; i < height / 2; i++) {
unsigned topFirstElement = i * imageRowBytes;
unsigned topLastElement = (i + 1) * imageRowBytes;
unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
| 172,502
|
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 expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, "w.ufdio");
umask(old_umask);
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59
|
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio");
umask(old_umask);
/* If reopening, make sure the file is what we expect */
if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
| 168,267
|
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: RenderThread::~RenderThread() {
FOR_EACH_OBSERVER(
RenderProcessObserver, observers_, OnRenderProcessShutdown());
if (web_database_observer_impl_.get())
web_database_observer_impl_->WaitForAllDatabasesToClose();
RemoveFilter(audio_input_message_filter_.get());
audio_input_message_filter_ = NULL;
RemoveFilter(audio_message_filter_.get());
audio_message_filter_ = NULL;
RemoveFilter(vc_manager_->video_capture_message_filter());
RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
if (file_thread_.get())
file_thread_->Stop();
if (webkit_client_.get())
WebKit::shutdown();
lazy_tls.Pointer()->Set(NULL);
#if defined(OS_WIN)
PluginChannelBase::CleanupChannels();
if (RenderProcessImpl::InProcessPlugins())
CoUninitialize();
#endif
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
RenderThread::~RenderThread() {
FOR_EACH_OBSERVER(
RenderProcessObserver, observers_, OnRenderProcessShutdown());
if (web_database_observer_impl_.get())
web_database_observer_impl_->WaitForAllDatabasesToClose();
RemoveFilter(devtools_agent_message_filter_.get());
devtools_agent_message_filter_ = NULL;
RemoveFilter(audio_input_message_filter_.get());
audio_input_message_filter_ = NULL;
RemoveFilter(audio_message_filter_.get());
audio_message_filter_ = NULL;
RemoveFilter(vc_manager_->video_capture_message_filter());
RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
if (file_thread_.get())
file_thread_->Stop();
if (webkit_client_.get())
WebKit::shutdown();
lazy_tls.Pointer()->Set(NULL);
#if defined(OS_WIN)
PluginChannelBase::CleanupChannels();
if (RenderProcessImpl::InProcessPlugins())
CoUninitialize();
#endif
}
| 170,327
|
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: SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
| 167,063
|
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 svc_rdma_get_write_arrays(struct rpcrdma_msg *rmsgp,
struct rpcrdma_write_array **write,
struct rpcrdma_write_array **reply)
{
__be32 *p;
p = (__be32 *)&rmsgp->rm_body.rm_chunks[0];
/* Read list */
while (*p++ != xdr_zero)
p += 5;
/* Write list */
if (*p != xdr_zero) {
*write = (struct rpcrdma_write_array *)p;
while (*p++ != xdr_zero)
p += 1 + be32_to_cpu(*p) * 4;
} else {
*write = NULL;
p++;
}
/* Reply chunk */
if (*p != xdr_zero)
*reply = (struct rpcrdma_write_array *)p;
else
*reply = NULL;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
static void svc_rdma_get_write_arrays(struct rpcrdma_msg *rmsgp,
static void svc_rdma_get_write_arrays(__be32 *rdma_argp,
__be32 **write, __be32 **reply)
{
__be32 *p;
p = rdma_argp + rpcrdma_fixed_maxsz;
/* Read list */
while (*p++ != xdr_zero)
p += 5;
/* Write list */
if (*p != xdr_zero) {
*write = p;
while (*p++ != xdr_zero)
p += 1 + be32_to_cpu(*p) * 4;
} else {
*write = NULL;
p++;
}
/* Reply chunk */
if (*p != xdr_zero)
*reply = p;
else
*reply = NULL;
}
| 168,172
|
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: cib_send_tls(gnutls_session * session, xmlNode * msg)
{
char *xml_text = NULL;
# if 0
const char *name = crm_element_name(msg);
if (safe_str_neq(name, "cib_command")) {
xmlNodeSetName(msg, "cib_result");
}
# endif
xml_text = dump_xml_unformatted(msg);
if (xml_text != NULL) {
char *unsent = xml_text;
int len = strlen(xml_text);
int rc = 0;
len++; /* null char */
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
crm_debug("Sent %d bytes", rc);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_debug("Connection terminated");
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
break;
}
}
}
free(xml_text);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_send_tls(gnutls_session * session, xmlNode * msg)
static int
crm_send_tls(gnutls_session * session, const char *buf, size_t len)
{
const char *unsent = buf;
int rc = 0;
int total_send;
if (buf == NULL) {
return -1;
}
total_send = len;
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_err("Connection terminated rc = %d", rc);
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
crm_debug("Sent %d bytes", rc);
break;
}
}
return rc < 0 ? rc : total_send;
}
| 166,161
|
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 bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
return false;
}
| 170,506
|
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 CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "PING"))
return;
reply(nickFromMask(prefix), "PING", param);
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix));
} else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
}
else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
}
}
Commit Message:
CWE ID: CWE-399
|
void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
reply = param;
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix));
} else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
}
else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
}
}
| 164,878
|
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 ExtensionTtsController::SetPlatformImpl(
ExtensionTtsPlatformImpl* platform_impl) {
platform_impl_ = platform_impl;
}
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
|
void ExtensionTtsController::SetPlatformImpl(
| 170,386
|
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: SPL_METHOD(SplFileObject, getCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter[2], enclosure[2];
array_init(return_value);
delimiter[0] = intern->u.file.delimiter;
delimiter[1] = '\0';
enclosure[0] = intern->u.file.enclosure;
enclosure[1] = '\0';
add_next_index_string(return_value, delimiter, 1);
add_next_index_string(return_value, enclosure, 1);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, getCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter[2], enclosure[2];
array_init(return_value);
delimiter[0] = intern->u.file.delimiter;
delimiter[1] = '\0';
enclosure[0] = intern->u.file.enclosure;
enclosure[1] = '\0';
add_next_index_string(return_value, delimiter, 1);
add_next_index_string(return_value, enclosure, 1);
}
| 167,064
|
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 license_read_scope_list(wStream* s, SCOPE_LIST* scopeList)
{
UINT32 i;
UINT32 scopeCount;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */
scopeList->count = scopeCount;
scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount);
/* ScopeArray */
for (i = 0; i < scopeCount; i++)
{
scopeList->array[i].type = BB_SCOPE_BLOB;
if (!license_read_binary_blob(s, &scopeList->array[i]))
return FALSE;
}
return TRUE;
}
Commit Message: Fix possible integer overflow in license_read_scope_list()
CWE ID: CWE-189
|
BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList)
{
UINT32 i;
UINT32 scopeCount;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */
if (Stream_GetRemainingLength(s) / sizeof(LICENSE_BLOB) < scopeCount)
return FALSE; /* Avoid overflow in malloc */
scopeList->count = scopeCount;
scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount);
/* ScopeArray */
for (i = 0; i < scopeCount; i++)
{
scopeList->array[i].type = BB_SCOPE_BLOB;
if (!license_read_binary_blob(s, &scopeList->array[i]))
return FALSE;
}
return TRUE;
}
| 166,440
|
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: report_error (const char *format, ...)
#else
report_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
error_prolog (1);
SH_VA_START (args, format);
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
va_end (args);
if (exit_immediately_on_error)
exit_shell (1);
}
Commit Message:
CWE ID: CWE-119
|
report_error (const char *format, ...)
#else
report_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
error_prolog (1);
SH_VA_START (args, format);
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
va_end (args);
if (exit_immediately_on_error)
{
if (last_command_exit_value == 0)
last_command_exit_value = 1;
exit_shell (last_command_exit_value);
}
}
| 165,430
|
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: SchedulerObject::hold(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-20
|
SchedulerObject::hold(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
| 164,832
|
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 AXNodeObject::isModal() const {
if (roleValue() != DialogRole && roleValue() != AlertDialogRole)
return false;
if (hasAttribute(aria_modalAttr)) {
const AtomicString& modal = getAttribute(aria_modalAttr);
if (equalIgnoringCase(modal, "true"))
return true;
if (equalIgnoringCase(modal, "false"))
return false;
}
if (getNode() && isHTMLDialogElement(*getNode()))
return toElement(getNode())->isInTopLayer();
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXNodeObject::isModal() const {
if (roleValue() != DialogRole && roleValue() != AlertDialogRole)
return false;
if (hasAttribute(aria_modalAttr)) {
const AtomicString& modal = getAttribute(aria_modalAttr);
if (equalIgnoringASCIICase(modal, "true"))
return true;
if (equalIgnoringASCIICase(modal, "false"))
return false;
}
if (getNode() && isHTMLDialogElement(*getNode()))
return toElement(getNode())->isInTopLayer();
return false;
}
| 171,916
|
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 ProcessStateChangesUnifiedPlan(
WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan);
handler_->OnModifyTransceivers(
std::move(states.transceiver_states),
action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION);
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#622945}
CWE ID: CWE-416
|
void ProcessStateChangesUnifiedPlan(
WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan);
if (handler_) {
handler_->OnModifyTransceivers(
std::move(states.transceiver_states),
action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION);
}
}
| 173,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: static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
*data = &iterator->current;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
*data = &iterator->current;
}
| 167,070
|
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 *path_name(const struct name_path *path, const char *name)
{
const struct name_path *p;
char *n, *m;
int nlen = strlen(name);
int len = nlen + 1;
for (p = path; p; p = p->up) {
if (p->elem_len)
len += p->elem_len + 1;
}
n = xmalloc(len);
m = n + len - (nlen + 1);
strcpy(m, name);
for (p = path; p; p = p->up) {
if (p->elem_len) {
m -= p->elem_len + 1;
memcpy(m, p->elem, p->elem_len);
m[p->elem_len] = '/';
}
}
return n;
}
Commit Message: prefer memcpy to strcpy
When we already know the length of a string (e.g., because
we just malloc'd to fit it), it's nicer to use memcpy than
strcpy, as it makes it more obvious that we are not going to
overflow the buffer (because the size we pass matches the
size in the allocation).
This also eliminates calls to strcpy, which make auditing
the code base harder.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CWE ID: CWE-119
|
char *path_name(const struct name_path *path, const char *name)
{
const struct name_path *p;
char *n, *m;
int nlen = strlen(name);
int len = nlen + 1;
for (p = path; p; p = p->up) {
if (p->elem_len)
len += p->elem_len + 1;
}
n = xmalloc(len);
m = n + len - (nlen + 1);
memcpy(m, name, nlen + 1);
for (p = path; p; p = p->up) {
if (p->elem_len) {
m -= p->elem_len + 1;
memcpy(m, p->elem, p->elem_len);
m[p->elem_len] = '/';
}
}
return n;
}
| 167,429
|
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: I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
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
|
I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage", "i18n",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
| 172,249
|
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 char *print_number( cJSON *item )
{
char *str;
double f, f2;
int64_t i;
str = (char*) cJSON_malloc( 64 );
if ( str ) {
f = item->valuefloat;
i = f;
f2 = i;
if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX )
sprintf( str, "%lld", (long long) item->valueint );
else
sprintf( str, "%g", item->valuefloat );
}
return str;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
static char *print_number( cJSON *item )
static int update(printbuffer *p)
{
char *str;
if (!p || !p->buffer) return 0;
str=p->buffer+p->offset;
return p->offset+strlen(str);
}
/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p)
{
char *str=0;
double d=item->valuedouble;
if (d==0)
{
if (p) str=ensure(p,2);
else str=(char*)cJSON_malloc(2); /* special case for 0. */
if (str) strcpy(str,"0");
}
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=LLONG_MAX && d>=LLONG_MIN)
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64);
if (str) sprintf(str,"%lld",(long long) item->valueint);
}
else
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
if (str)
{
if (fpclassify(d) != FP_ZERO && !isnormal(d)) sprintf(str,"null");
else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d);
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
else sprintf(str,"%f",d);
}
}
return str;
}
| 167,307
|
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 Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint();
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
R=haraken@chromium.org
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254
|
void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
| 171,944
|
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: network_init ()
{
#ifdef HAVE_GNUTLS
char *ca_path, *ca_path2;
gnutls_global_init ();
gnutls_certificate_allocate_credentials (&gnutls_xcred);
ca_path = string_expand_home (CONFIG_STRING(config_network_gnutls_ca_file));
if (ca_path)
{
ca_path2 = string_replace (ca_path, "%h", weechat_home);
if (ca_path2)
{
gnutls_certificate_set_x509_trust_file (gnutls_xcred, ca_path2,
GNUTLS_X509_FMT_PEM);
free (ca_path2);
}
free (ca_path);
}
gnutls_certificate_client_set_retrieve_function (gnutls_xcred,
&hook_connect_gnutls_set_certificates);
network_init_ok = 1;
gcry_check_version (GCRYPT_VERSION);
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
}
Commit Message:
CWE ID: CWE-20
|
network_init ()
{
#ifdef HAVE_GNUTLS
char *ca_path, *ca_path2;
gnutls_global_init ();
gnutls_certificate_allocate_credentials (&gnutls_xcred);
ca_path = string_expand_home (CONFIG_STRING(config_network_gnutls_ca_file));
if (ca_path)
{
ca_path2 = string_replace (ca_path, "%h", weechat_home);
if (ca_path2)
{
gnutls_certificate_set_x509_trust_file (gnutls_xcred, ca_path2,
GNUTLS_X509_FMT_PEM);
free (ca_path2);
}
free (ca_path);
}
gnutls_certificate_set_verify_function (gnutls_xcred,
&hook_connect_gnutls_verify_certificates);
gnutls_certificate_client_set_retrieve_function (gnutls_xcred,
&hook_connect_gnutls_set_certificates);
network_init_ok = 1;
gcry_check_version (GCRYPT_VERSION);
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
}
| 164,712
|
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 BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
listener_ = AudioListener::Create(*this);
}
}
Commit Message: Audio thread should not access destination node
The AudioDestinationNode is an object managed by Oilpan so the audio
thread should not access it. However, the audio thread needs
information (currentTime, etc) from the destination node. So instead
of accessing the audio destination handler (a scoped_refptr) via the
destination node, add a new member to the base audio context that
holds onto the destination handler.
The destination handler is not an oilpan object and lives at least as
long as the base audio context.
Bug: 860626, 860522, 863951
Test: Test case from 860522 doesn't crash on asan build
Change-Id: I3add844d4eb8fdc7e05b89292938b843a0abbb99
Reviewed-on: https://chromium-review.googlesource.com/1138974
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#575509}
CWE ID: CWE-416
|
void BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
// TODO(crbug.com/863951). The audio thread needs some things from the
// destination handler like the currentTime. But the audio thread
// shouldn't access the |destination_node_| since it's an Oilpan object.
// Thus, get the destination handler, a non-oilpan object, so we can get
// the items directly from the handler instead of through the destination
// node.
destination_handler_ = &destination_node_->GetAudioDestinationHandler();
listener_ = AudioListener::Create(*this);
}
}
| 173,175
|
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 skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
Commit Message: security fix
CWE ID: CWE-269
|
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
| 168,371
|
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 Reset() {
error_nframes_ = 0;
droppable_nframes_ = 0;
}
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 Reset() {
error_nframes_ = 0;
droppable_nframes_ = 0;
pattern_switch_ = 0;
}
| 174,543
|
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: Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment, idx, element_start);
assert(pCluster);
return pCluster;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) {
if (!pSegment || off < 0)
return NULL;
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster =
new (std::nothrow) Cluster(pSegment, idx, element_start);
return pCluster;
}
| 173,804
|
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 GfxIndexedColorSpace::getRGBLine(Guchar *in, unsigned int *out, int length) {
Guchar *line;
int i, j, n;
n = base->getNComps();
line = (Guchar *) gmalloc (length * n);
for (i = 0; i < length; i++)
for (j = 0; j < n; j++)
line[i * n + j] = lookup[in[i] * n + j];
base->getRGBLine(line, out, length);
gfree (line);
}
Commit Message:
CWE ID: CWE-189
|
void GfxIndexedColorSpace::getRGBLine(Guchar *in, unsigned int *out, int length) {
Guchar *line;
int i, j, n;
n = base->getNComps();
line = (Guchar *) gmallocn (length, n);
for (i = 0; i < length; i++)
for (j = 0; j < n; j++)
line[i * n + j] = lookup[in[i] * n + j];
base->getRGBLine(line, out, length);
gfree (line);
}
| 164,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: static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&control->id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Jaroslav Kysela <perex@perex.cz>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
struct snd_ctl_elem_id id = control->id;
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
| 166,293
|
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 btsnoop_write(const void *data, size_t length) {
if (logfile_fd != INVALID_FD)
write(logfile_fd, data, length);
btsnoop_net_write(data, length);
}
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
|
static void btsnoop_write(const void *data, size_t length) {
if (logfile_fd != INVALID_FD)
TEMP_FAILURE_RETRY(write(logfile_fd, data, length));
btsnoop_net_write(data, length);
}
| 173,472
|
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: P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
quic::QuicSession* session)
: quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
|
P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
| 172,263
|
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 SavePackage::OnReceivedSavableResourceLinksForCurrentPage(
const std::vector<GURL>& resources_list,
const std::vector<Referrer>& referrers_list,
const std::vector<GURL>& frames_list) {
if (wait_state_ != RESOURCES_LIST)
return;
DCHECK(resources_list.size() == referrers_list.size());
all_save_items_count_ = static_cast<int>(resources_list.size()) +
static_cast<int>(frames_list.size());
if (download_ && download_->IsInProgress())
download_->SetTotalBytes(all_save_items_count_);
if (all_save_items_count_) {
for (int i = 0; i < static_cast<int>(resources_list.size()); ++i) {
const GURL& u = resources_list[i];
DCHECK(u.is_valid());
SaveFileCreateInfo::SaveFileSource save_source = u.SchemeIsFile() ?
SaveFileCreateInfo::SAVE_FILE_FROM_FILE :
SaveFileCreateInfo::SAVE_FILE_FROM_NET;
SaveItem* save_item = new SaveItem(u, referrers_list[i],
this, save_source);
waiting_item_queue_.push(save_item);
}
for (int i = 0; i < static_cast<int>(frames_list.size()); ++i) {
const GURL& u = frames_list[i];
DCHECK(u.is_valid());
SaveItem* save_item = new SaveItem(
u, Referrer(), this, SaveFileCreateInfo::SAVE_FILE_FROM_DOM);
waiting_item_queue_.push(save_item);
}
wait_state_ = NET_FILES;
DoSavingProcess();
} else {
Cancel(true);
}
}
Commit Message: Fix crash with mismatched vector sizes.
BUG=169295
Review URL: https://codereview.chromium.org/11817050
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176252 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void SavePackage::OnReceivedSavableResourceLinksForCurrentPage(
const std::vector<GURL>& resources_list,
const std::vector<Referrer>& referrers_list,
const std::vector<GURL>& frames_list) {
if (wait_state_ != RESOURCES_LIST)
return;
if (resources_list.size() != referrers_list.size())
return;
all_save_items_count_ = static_cast<int>(resources_list.size()) +
static_cast<int>(frames_list.size());
if (download_ && download_->IsInProgress())
download_->SetTotalBytes(all_save_items_count_);
if (all_save_items_count_) {
for (int i = 0; i < static_cast<int>(resources_list.size()); ++i) {
const GURL& u = resources_list[i];
DCHECK(u.is_valid());
SaveFileCreateInfo::SaveFileSource save_source = u.SchemeIsFile() ?
SaveFileCreateInfo::SAVE_FILE_FROM_FILE :
SaveFileCreateInfo::SAVE_FILE_FROM_NET;
SaveItem* save_item = new SaveItem(u, referrers_list[i],
this, save_source);
waiting_item_queue_.push(save_item);
}
for (int i = 0; i < static_cast<int>(frames_list.size()); ++i) {
const GURL& u = frames_list[i];
DCHECK(u.is_valid());
SaveItem* save_item = new SaveItem(
u, Referrer(), this, SaveFileCreateInfo::SAVE_FILE_FROM_DOM);
waiting_item_queue_.push(save_item);
}
wait_state_ = NET_FILES;
DoSavingProcess();
} else {
Cancel(true);
}
}
| 171,400
|
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 bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) {
pthread_mutex_lock(&slot_lock);
uint32_t id = (uintptr_t)user_data;
int ret = false;
rfc_slot_t *slot = find_rfc_slot_by_id(id);
if (!slot)
goto out;
int received = recv(slot->fd, buf, size, 0);
if(received == size) {
ret = true;
} else {
LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__, strerror(errno));
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
return ret;
}
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 bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) {
pthread_mutex_lock(&slot_lock);
uint32_t id = (uintptr_t)user_data;
int ret = false;
rfc_slot_t *slot = find_rfc_slot_by_id(id);
if (!slot)
goto out;
int received = TEMP_FAILURE_RETRY(recv(slot->fd, buf, size, 0));
if(received == size) {
ret = true;
} else {
LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__, strerror(errno));
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
return ret;
}
| 173,455
|
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: pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = calloc(1, sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = malloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = malloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
|
pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = safe_calloc(sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = safe_calloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = safe_calloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
| 169,573
|
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 re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476
|
static void re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
| 168,482
|
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: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID:
|
RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
| 172,147
|
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 db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(&svm->vcpu);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <jbeulich@suse.com>
Cc: stable@vger.kernel.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-399
|
static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
| 166,568
|
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 locationWithPerWorldBindingsAttributeSetterForMainWorld(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 locationWithPerWorldBindingsAttributeSetterForMainWorld(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,690
|
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: long Cues::GetCount() const
{
if (m_cue_points == NULL)
return -1;
return m_count; //TODO: really ignore preload count?
}
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
|
long Cues::GetCount() const
const long long stop = m_start + m_size;
| 174,298
|
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 RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions())
return false;
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(false /* browser_only */)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor) &&
!base::FeatureList::IsEnabled(
features::kUseVideoCaptureApiForDevToolsSnapshots)) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
}
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
Commit Message: [DevTools] Do not create target handler for restricted sessions
Bug: 805224
Change-Id: I08528e44e79d0a097cfe72ab4949dda538efd098
Reviewed-on: https://chromium-review.googlesource.com/988695
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Commit-Queue: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547496}
CWE ID: CWE-20
|
bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions())
return false;
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
if (!session->restricted()) {
session->AddHandler(base::WrapUnique(
new protocol::TargetHandler(false /* browser_only */)));
}
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor) &&
!base::FeatureList::IsEnabled(
features::kUseVideoCaptureApiForDevToolsSnapshots)) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
}
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
| 173,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: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
version_ = GET_PARAM(2); // 0: high precision forward transform
}
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
|
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
version_ = GET_PARAM(2); // 0: high precision forward transform
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,531
|
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 PersistentHistogramAllocator::RecordCreateHistogramResult(
CreateHistogramResultType result) {
HistogramBase* result_histogram = GetCreateHistogramResultHistogram();
if (result_histogram)
result_histogram->Add(result);
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
void PersistentHistogramAllocator::RecordCreateHistogramResult(
| 172,135
|
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 _mkp_stage_30(struct plugin *p,
struct client_session *cs,
struct session_request *sr)
{
mk_ptr_t referer;
(void) p;
(void) cs;
PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket);
if (mk_security_check_url(sr->uri) < 0) {
PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket);
mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN);
return MK_PLUGIN_RET_CLOSE_CONX;
}
PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket);
referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer"));
if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) {
PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket);
mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN);
return MK_PLUGIN_RET_CLOSE_CONX;
}
return MK_PLUGIN_RET_NOT_ME;
}
Commit Message: Mandril: check decoded URI (fix #92)
Signed-off-by: Eduardo Silva <eduardo@monkey.io>
CWE ID: CWE-264
|
int _mkp_stage_30(struct plugin *p,
struct client_session *cs,
struct session_request *sr)
{
mk_ptr_t referer;
(void) p;
(void) cs;
PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket);
if (mk_security_check_url(sr->uri_processed) < 0) {
PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket);
mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN);
return MK_PLUGIN_RET_CLOSE_CONX;
}
PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket);
referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer"));
if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) {
PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket);
mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN);
return MK_PLUGIN_RET_CLOSE_CONX;
}
return MK_PLUGIN_RET_NOT_ME;
}
| 166,545
|
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 ChromeMockRenderThread::OnDidPrintPage(
const PrintHostMsg_DidPrintPage_Params& params) {
if (printer_.get())
printer_->PrintPage(params);
}
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 ChromeMockRenderThread::OnDidPrintPage(
const PrintHostMsg_DidPrintPage_Params& params) {
printer_->PrintPage(params);
}
| 170,850
|
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 ContentSecurityPolicy::AllowPluginTypeForDocument(
const Document& document,
const String& type,
const String& type_attribute,
const KURL& url,
SecurityViolationReportingPolicy reporting_policy) const {
if (document.GetContentSecurityPolicy() &&
!document.GetContentSecurityPolicy()->AllowPluginType(
type, type_attribute, url, reporting_policy))
return false;
LocalFrame* frame = document.GetFrame();
if (frame && frame->Tree().Parent() && document.IsPluginDocument()) {
ContentSecurityPolicy* parent_csp = frame->Tree()
.Parent()
->GetSecurityContext()
->GetContentSecurityPolicy();
if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url,
reporting_policy))
return false;
}
return true;
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
|
bool ContentSecurityPolicy::AllowPluginTypeForDocument(
const Document& document,
const String& type,
const String& type_attribute,
const KURL& url,
SecurityViolationReportingPolicy reporting_policy) const {
if (document.GetContentSecurityPolicy() &&
!document.GetContentSecurityPolicy()->AllowPluginType(
type, type_attribute, url, reporting_policy))
return false;
return true;
}
| 173,055
|
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_get_hash (MyObject *obj, GHashTable **ret, GError **error)
{
GHashTable *table;
table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (table, "foo", "bar");
g_hash_table_insert (table, "baz", "whee");
g_hash_table_insert (table, "cow", "crack");
*ret = table;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_get_hash (MyObject *obj, GHashTable **ret, GError **error)
| 165,100
|
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 l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sock *sk = sock->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk);
lsa->l2tp_family = AF_INET6;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
if (peer) {
if (!lsk->peer_conn_id)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr = np->daddr;
if (np->sndflow)
lsa->l2tp_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&np->rcv_saddr))
lsa->l2tp_addr = np->saddr;
else
lsa->l2tp_addr = np->rcv_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
}
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = sk->sk_bound_dev_if;
*uaddr_len = sizeof(*lsa);
return 0;
}
Commit Message: l2tp: fix info leak via getsockname()
The L2TP code for IPv6 fails to initialize the l2tp_unused member of
struct sockaddr_l2tpip6 and that for leaks two bytes kernel stack via
the getsockname() syscall. Initialize l2tp_unused with 0 to avoid the
info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: James Chapman <jchapman@katalix.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sock *sk = sock->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk);
lsa->l2tp_family = AF_INET6;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
lsa->l2tp_unused = 0;
if (peer) {
if (!lsk->peer_conn_id)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr = np->daddr;
if (np->sndflow)
lsa->l2tp_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&np->rcv_saddr))
lsa->l2tp_addr = np->saddr;
else
lsa->l2tp_addr = np->rcv_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
}
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = sk->sk_bound_dev_if;
*uaddr_len = sizeof(*lsa);
return 0;
}
| 166,183
|
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: long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
return 0;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
|
long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
return 0;
}
| 173,988
|
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_msgtype_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%s", tok2str(l2tp_msgtype2str, "MSGTYPE-#%u",
EXTRACT_16BITS(ptr))));
}
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_msgtype_print(netdissect_options *ndo, const u_char *dat)
l2tp_msgtype_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ND_PRINT((ndo, "%s", tok2str(l2tp_msgtype2str, "MSGTYPE-#%u",
EXTRACT_16BITS(ptr))));
}
| 167,896
|
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: long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos,
long& len) {
assert(pReader);
assert(pos >= 0);
long long total, available;
int status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
len = 1;
if (pos >= available)
return pos; // too few bytes available
unsigned char b;
status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
assert(status == 0);
if (b == 0) // we can't handle u-int values larger than 8 bytes
return E_FILE_FORMAT_INVALID;
unsigned char m = 0x80;
while (!(b & m)) {
m >>= 1;
++len;
}
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos,
long long ReadID(IMkvReader* pReader, long long pos, long& len) {
const long long id = ReadUInt(pReader, pos, len);
if (id < 0 || len < 1 || len > 4) {
// An ID must be at least 1 byte long, and cannot exceed 4.
// See EBMLMaxIDLength: http://www.matroska.org/technical/specs/index.html
return E_FILE_FORMAT_INVALID;
}
return id;
}
long long GetUIntLength(IMkvReader* pReader, long long pos, long& len) {
if (!pReader || pos < 0)
return E_FILE_FORMAT_INVALID;
long long total, available;
int status = pReader->Length(&total, &available);
if (status < 0 || (total >= 0 && available > total))
return E_FILE_FORMAT_INVALID;
len = 1;
if (pos >= available)
return pos; // too few bytes available
unsigned char b;
status = pReader->Read(pos, 1, &b);
if (status != 0)
return status;
if (b == 0) // we can't handle u-int values larger than 8 bytes
return E_FILE_FORMAT_INVALID;
unsigned char m = 0x80;
while (!(b & m)) {
m >>= 1;
++len;
}
return 0; // success
}
| 173,824
|
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 GM2TabStyle::PaintTab(gfx::Canvas* canvas, const SkPath& clip) const {
int active_tab_fill_id = 0;
int active_tab_y_inset = 0;
if (tab_->GetThemeProvider()->HasCustomImage(IDR_THEME_TOOLBAR)) {
active_tab_fill_id = IDR_THEME_TOOLBAR;
active_tab_y_inset = GetStrokeThickness(true);
}
if (tab_->IsActive()) {
PaintTabBackground(canvas, true /* active */, active_tab_fill_id,
active_tab_y_inset, nullptr /* clip */);
} else {
PaintInactiveTabBackground(canvas, clip);
const float throb_value = GetThrobValue();
if (throb_value > 0) {
canvas->SaveLayerAlpha(gfx::ToRoundedInt(throb_value * 0xff),
tab_->GetLocalBounds());
PaintTabBackground(canvas, true /* active */, active_tab_fill_id,
active_tab_y_inset, nullptr /* clip */);
canvas->Restore();
}
}
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <bsep@chromium.org>
Reviewed-by: Taylor Bergquist <tbergquist@chromium.org>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
|
void GM2TabStyle::PaintTab(gfx::Canvas* canvas, const SkPath& clip) const {
int active_tab_fill_id = 0;
int active_tab_y_inset = 0;
if (tab_->GetThemeProvider()->HasCustomImage(IDR_THEME_TOOLBAR)) {
active_tab_fill_id = IDR_THEME_TOOLBAR;
active_tab_y_inset = GetStrokeThickness(true);
}
if (tab_->IsActive()) {
PaintTabBackground(canvas, TAB_ACTIVE, active_tab_fill_id,
active_tab_y_inset, nullptr /* clip */);
} else {
PaintInactiveTabBackground(canvas, clip);
const float throb_value = GetThrobValue();
if (throb_value > 0) {
canvas->SaveLayerAlpha(gfx::ToRoundedInt(throb_value * 0xff),
tab_->GetLocalBounds());
PaintTabBackground(canvas, TAB_ACTIVE, active_tab_fill_id,
active_tab_y_inset, nullptr /* clip */);
canvas->Restore();
}
}
}
| 172,524
|
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: AppControllerImpl::AppControllerImpl(Profile* profile)
//// static
: profile_(profile),
app_service_proxy_(apps::AppServiceProxy::Get(profile)),
url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
chromeos::switches::kKioskNextHomeUrlPrefix)) {
app_service_proxy_->AppRegistryCache().AddObserver(this);
if (profile) {
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <michaelpg@chromium.org>
Commit-Queue: Lucas Tenório <ltenorio@chromium.org>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
|
AppControllerImpl::AppControllerImpl(Profile* profile)
//// static
AppControllerService* AppControllerService::Get(
content::BrowserContext* context) {
return AppControllerServiceFactory::GetForBrowserContext(context);
}
AppControllerService::AppControllerService(Profile* profile)
: profile_(profile),
app_service_proxy_(apps::AppServiceProxy::Get(profile)),
url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
chromeos::switches::kKioskNextHomeUrlPrefix)) {
DCHECK(profile);
app_service_proxy_->AppRegistryCache().AddObserver(this);
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
| 172,079
|
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 registerBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->blobData.release());
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
static void registerBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry()) {
WebBlobData webBlobData(blobRegistryContext->blobData.release());
registry->registerBlobURL(blobRegistryContext->url, webBlobData);
}
}
| 170,687
|
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 jas_stream_gobble(jas_stream_t *stream, int n)
{
int m;
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_getc(stream) == EOF) {
return n - m;
}
}
return n;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190
|
int jas_stream_gobble(jas_stream_t *stream, int n)
{
int m;
if (n < 0) {
jas_deprecated("negative count for jas_stream_gobble");
}
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_getc(stream) == EOF) {
return n - m;
}
}
return n;
}
| 168,745
|
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 char *string_of_NPNVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPNVxDisplay);
_(NPNVxtAppContext);
_(NPNVnetscapeWindow);
_(NPNVjavascriptEnabledBool);
_(NPNVasdEnabledBool);
_(NPNVisOfflineBool);
_(NPNVserviceManager);
_(NPNVDOMElement);
_(NPNVDOMWindow);
_(NPNVToolkit);
_(NPNVSupportsXEmbedBool);
_(NPNVWindowNPObject);
_(NPNVPluginElementNPObject);
_(NPNVSupportsWindowless);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPNVserviceManager);
_(11, NPNVDOMElement);
_(12, NPNVDOMWindow);
_(13, NPNVToolkit);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264
|
const char *string_of_NPNVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPNVxDisplay);
_(NPNVxtAppContext);
_(NPNVnetscapeWindow);
_(NPNVjavascriptEnabledBool);
_(NPNVasdEnabledBool);
_(NPNVisOfflineBool);
_(NPNVserviceManager);
_(NPNVDOMElement);
_(NPNVDOMWindow);
_(NPNVToolkit);
_(NPNVSupportsXEmbedBool);
_(NPNVWindowNPObject);
_(NPNVPluginElementNPObject);
_(NPNVSupportsWindowless);
_(NPNVprivateModeBool);
_(NPNVsupportsAdvancedKeyHandling);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPNVserviceManager);
_(11, NPNVDOMElement);
_(12, NPNVDOMWindow);
_(13, NPNVToolkit);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
| 165,865
|
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 ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
base::CommandLine* singleton_command_line =
base::CommandLine::ForCurrentProcess();
if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitch(::switches::kDisableSync);
singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
browser_defaults::bookmarks_enabled = false;
}
if (!base::SysInfo::IsRunningOnChromeOS() &&
!parsed_command_line().HasSwitch(switches::kLoginManager) &&
!parsed_command_line().HasSwitch(switches::kLoginUser) &&
!parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitchASCII(
switches::kLoginUser,
cryptohome::Identification(user_manager::StubAccountId()).id());
if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
chrome::kTestUserProfileDir);
}
LOG(WARNING) << "Running as stub user with profile dir: "
<< singleton_command_line
->GetSwitchValuePath(switches::kLoginProfile)
.value();
}
RegisterStubPathOverridesIfNecessary();
#if defined(GOOGLE_CHROME_BUILD)
const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
std::string channel;
if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
chrome::SetChannel(channel);
#endif
dbus_pre_early_init_ = std::make_unique<internal::DBusPreEarlyInit>();
return ChromeBrowserMainPartsLinux::PreEarlyInitialization();
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <xiyuan@chromium.org>
Commit-Queue: Sam McNally <sammc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID:
|
int ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
base::CommandLine* singleton_command_line =
base::CommandLine::ForCurrentProcess();
if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitch(::switches::kDisableSync);
singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
browser_defaults::bookmarks_enabled = false;
}
if (!base::SysInfo::IsRunningOnChromeOS() &&
!parsed_command_line().HasSwitch(switches::kLoginManager) &&
!parsed_command_line().HasSwitch(switches::kLoginUser) &&
!parsed_command_line().HasSwitch(switches::kGuestSession)) {
singleton_command_line->AppendSwitchASCII(
switches::kLoginUser,
cryptohome::Identification(user_manager::StubAccountId()).id());
if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
chrome::kTestUserProfileDir);
}
LOG(WARNING) << "Running as stub user with profile dir: "
<< singleton_command_line
->GetSwitchValuePath(switches::kLoginProfile)
.value();
}
RegisterStubPathOverridesIfNecessary();
#if defined(GOOGLE_CHROME_BUILD)
const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
std::string channel;
if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
chrome::SetChannel(channel);
#endif
dbus_pre_early_init_ = std::make_unique<internal::DBusPreEarlyInit>();
if (!base::SysInfo::IsRunningOnChromeOS() &&
parsed_command_line().HasSwitch(
switches::kFakeDriveFsLauncherChrootPath) &&
parsed_command_line().HasSwitch(
switches::kFakeDriveFsLauncherSocketPath)) {
drivefs::FakeDriveFsLauncherClient::Init(
parsed_command_line().GetSwitchValuePath(
switches::kFakeDriveFsLauncherChrootPath),
parsed_command_line().GetSwitchValuePath(
switches::kFakeDriveFsLauncherSocketPath));
}
return ChromeBrowserMainPartsLinux::PreEarlyInitialization();
}
| 171,728
|
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 LocalFileSystem::deleteFileSystemInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
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
|
void LocalFileSystem::deleteFileSystemInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
CallbackWrapper* callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
| 171,425
|
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 ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, 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
|
void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
| 170,979
|
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 SelectionEditor::NodeWillBeRemoved(Node& node_to_be_removed) {
if (selection_.IsNone())
return;
const Position old_base = selection_.base_;
const Position old_extent = selection_.extent_;
const Position& new_base =
ComputePositionForNodeRemoval(old_base, node_to_be_removed);
const Position& new_extent =
ComputePositionForNodeRemoval(old_extent, node_to_be_removed);
if (new_base == old_base && new_extent == old_extent)
return;
selection_ = SelectionInDOMTree::Builder()
.SetBaseAndExtent(new_base, new_extent)
.SetIsHandleVisible(selection_.IsHandleVisible())
.Build();
MarkCacheDirty();
}
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 SelectionEditor::NodeWillBeRemoved(Node& node_to_be_removed) {
if (selection_.IsNone())
return;
const Position old_base = selection_.base_;
const Position old_extent = selection_.extent_;
const Position& new_base =
ComputePositionForNodeRemoval(old_base, node_to_be_removed);
const Position& new_extent =
ComputePositionForNodeRemoval(old_extent, node_to_be_removed);
if (new_base == old_base && new_extent == old_extent)
return;
selection_ = SelectionInDOMTree::Builder()
.SetBaseAndExtent(new_base, new_extent)
.Build();
MarkCacheDirty();
}
| 171,765
|
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 skt_read(int fd, void *p, size_t len)
{
int read;
struct pollfd pfd;
struct timespec ts;
FNLOG();
ts_log("skt_read recv", len, NULL);
if ((read = recv(fd, p, len, MSG_NOSIGNAL)) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return read;
}
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
|
static int skt_read(int fd, void *p, size_t len)
{
int read;
struct pollfd pfd;
struct timespec ts;
FNLOG();
ts_log("skt_read recv", len, NULL);
if ((read = TEMP_FAILURE_RETRY(recv(fd, p, len, MSG_NOSIGNAL))) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return read;
}
| 173,428
|
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 coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
Commit Message:
CWE ID: CWE-399
|
static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
g_free(xattr_fidp->fs.xattr.value);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
| 164,909
|
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 void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,556
|
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 TracingControllerImpl::StartTracing(
const base::trace_event::TraceConfig& trace_config,
StartTracingDoneCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (IsTracing()) {
if (trace_config.process_filter_config().empty() ||
trace_config_->process_filter_config().empty()) {
return false;
}
base::trace_event::TraceConfig old_config_copy(*trace_config_);
base::trace_event::TraceConfig new_config_copy(trace_config);
old_config_copy.SetProcessFilterConfig(
base::trace_event::TraceConfig::ProcessFilterConfig());
new_config_copy.SetProcessFilterConfig(
base::trace_event::TraceConfig::ProcessFilterConfig());
if (old_config_copy.ToString() != new_config_copy.ToString())
return false;
}
trace_config_ =
std::make_unique<base::trace_event::TraceConfig>(trace_config);
start_tracing_done_ = std::move(callback);
ConnectToServiceIfNeeded();
coordinator_->StartTracing(trace_config.ToString());
if (start_tracing_done_ &&
(base::trace_event::TraceLog::GetInstance()->IsEnabled() ||
!trace_config.process_filter_config().IsEnabled(
base::Process::Current().Pid()))) {
std::move(start_tracing_done_).Run();
}
return true;
}
Commit Message: Tracing: Connect to service on startup
Temporary workaround for flaky tests introduced by
https://chromium-review.googlesource.com/c/chromium/src/+/1439082
TBR=eseckler@chromium.org
Bug: 928410, 928363
Change-Id: I0dcf20cbdf91a7beea167a220ba9ef7e0604c1ab
Reviewed-on: https://chromium-review.googlesource.com/c/1452767
Reviewed-by: oysteine <oysteine@chromium.org>
Reviewed-by: Eric Seckler <eseckler@chromium.org>
Reviewed-by: Aaron Gable <agable@chromium.org>
Commit-Queue: oysteine <oysteine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#631052}
CWE ID: CWE-19
|
bool TracingControllerImpl::StartTracing(
const base::trace_event::TraceConfig& trace_config,
StartTracingDoneCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (IsTracing()) {
if (trace_config.process_filter_config().empty() ||
trace_config_->process_filter_config().empty()) {
return false;
}
base::trace_event::TraceConfig old_config_copy(*trace_config_);
base::trace_event::TraceConfig new_config_copy(trace_config);
old_config_copy.SetProcessFilterConfig(
base::trace_event::TraceConfig::ProcessFilterConfig());
new_config_copy.SetProcessFilterConfig(
base::trace_event::TraceConfig::ProcessFilterConfig());
if (old_config_copy.ToString() != new_config_copy.ToString())
return false;
}
trace_config_ =
std::make_unique<base::trace_event::TraceConfig>(trace_config);
start_tracing_done_ = std::move(callback);
coordinator_->StartTracing(trace_config.ToString());
if (start_tracing_done_ &&
(base::trace_event::TraceLog::GetInstance()->IsEnabled() ||
!trace_config.process_filter_config().IsEnabled(
base::Process::Current().Pid()))) {
std::move(start_tracing_done_).Run();
}
return true;
}
| 172,056
|
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: ContentEncoding::GetEncryptionByIndex(unsigned long idx) const {
const ptrdiff_t count = encryption_entries_end_ - encryption_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return encryption_entries_[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
|
ContentEncoding::GetEncryptionByIndex(unsigned long idx) const {
const ContentEncoding::ContentEncryption* ContentEncoding::GetEncryptionByIndex(
unsigned long idx) const {
const ptrdiff_t count = encryption_entries_end_ - encryption_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return encryption_entries_[idx];
}
| 174,313
|
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 TestAppendTabsToTabStrip(bool focus_tab_strip) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit,
&second_lifecycle_unit);
const base::TimeTicks first_tab_last_focused_time =
first_lifecycle_unit->GetLastFocusedTime();
const base::TimeTicks second_tab_last_focused_time =
second_lifecycle_unit->GetLastFocusedTime();
task_runner_->FastForwardBy(kShortDelay);
LifecycleUnit* third_lifecycle_unit = nullptr;
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_))
.WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) {
third_lifecycle_unit = lifecycle_unit;
if (focus_tab_strip) {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_TRUE(IsFocused(second_lifecycle_unit));
} else {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_EQ(second_tab_last_focused_time,
second_lifecycle_unit->GetLastFocusedTime());
}
EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime());
}));
std::unique_ptr<content::WebContents> third_web_contents =
CreateAndNavigateWebContents();
content::WebContents* raw_third_web_contents = third_web_contents.get();
tab_strip_model_->AppendWebContents(std::move(third_web_contents), false);
testing::Mock::VerifyAndClear(&source_observer_);
EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents));
CloseTabsAndExpectNotifications(
tab_strip_model_.get(),
{first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit});
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void TestAppendTabsToTabStrip(bool focus_tab_strip) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit,
&second_lifecycle_unit);
const base::TimeTicks first_tab_last_focused_time =
first_lifecycle_unit->GetLastFocusedTime();
const base::TimeTicks second_tab_last_focused_time =
second_lifecycle_unit->GetLastFocusedTime();
task_runner_->FastForwardBy(kShortDelay);
LifecycleUnit* third_lifecycle_unit = nullptr;
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_))
.WillOnce(::testing::Invoke([&](LifecycleUnit* lifecycle_unit) {
third_lifecycle_unit = lifecycle_unit;
if (focus_tab_strip) {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_TRUE(IsFocused(second_lifecycle_unit));
} else {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_EQ(second_tab_last_focused_time,
second_lifecycle_unit->GetLastFocusedTime());
}
EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime());
}));
std::unique_ptr<content::WebContents> third_web_contents =
CreateAndNavigateWebContents();
content::WebContents* raw_third_web_contents = third_web_contents.get();
tab_strip_model_->AppendWebContents(std::move(third_web_contents), false);
::testing::Mock::VerifyAndClear(&source_observer_);
EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents));
CloseTabsAndExpectNotifications(
tab_strip_model_.get(),
{first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit});
}
| 172,227
|
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 raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
ret = copy_to_user(param, ptr, sizeof(*ptr));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output
Do not leak kernel-only floppy_raw_cmd structure members to userspace.
This includes the linked-list pointer and the pointer to the allocated
DMA space.
Signed-off-by: Matthew Daley <mattd@bugfuzz.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264
|
static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
struct floppy_raw_cmd cmd = *ptr;
cmd.next = NULL;
cmd.kernel_data = NULL;
ret = copy_to_user(param, &cmd, sizeof(cmd));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
| 166,434
|
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 BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
{
RefPtr<HTMLInputElement> protector(element());
element()->setFocus(false);
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
{
if (containsFocusedShadowElement())
return;
RefPtr<HTMLInputElement> protector(element());
element()->setFocus(false);
}
| 171,211
|
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 MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
{
ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(fd, offset, length))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476
|
status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
{
ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(fd, offset, length))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
| 173,538
|
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 GDataRootDirectory::ParseFromString(const std::string& serialized_proto) {
scoped_ptr<GDataRootDirectoryProto> proto(
new GDataRootDirectoryProto());
bool ok = proto->ParseFromString(serialized_proto);
if (ok) {
const std::string& title = proto->gdata_directory().gdata_entry().title();
if (title != "drive") {
LOG(ERROR) << "Incompatible proto detected: " << title;
return false;
}
FromProto(*proto.get());
set_origin(FROM_CACHE);
set_refresh_time(base::Time::Now());
}
return ok;
}
Commit Message: gdata: Define the resource ID for the root directory
Per the spec, the resource ID for the root directory is defined
as "folder:root". Add the resource ID to the root directory in our
file system representation so we can look up the root directory by
the resource ID.
BUG=127697
TEST=add unit tests
Review URL: https://chromiumcodereview.appspot.com/10332253
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool GDataRootDirectory::ParseFromString(const std::string& serialized_proto) {
scoped_ptr<GDataRootDirectoryProto> proto(
new GDataRootDirectoryProto());
bool ok = proto->ParseFromString(serialized_proto);
if (ok) {
const GDataEntryProto& entry_proto =
proto->gdata_directory().gdata_entry();
if (entry_proto.title() != "drive") {
LOG(ERROR) << "Incompatible proto detected (bad title): "
<< entry_proto.title();
return false;
}
// The title field for the root directory was originally empty. Discard
// the proto data if the older format is detected.
if (entry_proto.resource_id() != kGDataRootDirectoryResourceId) {
LOG(ERROR) << "Incompatible proto detected (bad resource ID): "
<< entry_proto.resource_id();
return false;
}
FromProto(*proto.get());
set_origin(FROM_CACHE);
set_refresh_time(base::Time::Now());
}
return ok;
}
| 170,778
|
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 check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
}
Commit Message:
CWE ID: CWE-20
|
static int check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) || check_newline(progname, dir))
return EX_USAGE;
return 0;
}
| 164,662
|
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 RunInvAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
double out_r[kNumCoeffs];
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
in[j] = src[j] - dst[j];
}
reference_16x16_dct_2d(in, out_r);
for (int j = 0; j < kNumCoeffs; ++j)
coeff[j] = round(out_r[j]);
REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
EXPECT_GE(1u, error)
<< "Error: 16x16 IDCT has error " << error
<< " at index " << j;
}
}
}
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 RunInvAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif // CONFIG_VP9_HIGHBITDEPTH
for (int i = 0; i < count_test_block; ++i) {
double out_r[kNumCoeffs];
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
in[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
in[j] = src16[j] - dst16[j];
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
reference_16x16_dct_2d(in, out_r);
for (int j = 0; j < kNumCoeffs; ++j)
coeff[j] = static_cast<tran_low_t>(round(out_r[j]));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16),
16));
#endif // CONFIG_VP9_HIGHBITDEPTH
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const uint32_t diff = dst[j] - src[j];
#endif // CONFIG_VP9_HIGHBITDEPTH
const uint32_t error = diff * diff;
EXPECT_GE(1u, error)
<< "Error: 16x16 IDCT has error " << error
<< " at index " << j;
}
}
}
| 174,523
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.