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 ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
resolver->resolve(imageBitmap);
return promise;
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
if (imageBitmap) {
resolver->resolve(imageBitmap);
} else {
v8::Isolate* isolate = ScriptState::current()->isolate();
resolver->reject(ScriptValue(v8::Null(isolate), isolate));
}
return promise;
}
| 171,395
|
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 destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
#ifdef CONFIG_SMP
free_percpu(s->s_files);
#endif
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
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
|
static void destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
| 166,807
|
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: AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title)
: valid_(true),
native_dialog_(NULL),
title_(title),
web_contents_(web_contents) {
}
Commit Message: Fix a Windows crash bug with javascript alerts from extension popups.
BUG=137707
Review URL: https://chromiumcodereview.appspot.com/10828423
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title)
: valid_(true),
native_dialog_(NULL),
title_(title),
web_contents_(web_contents),
completed_(false) {
}
| 170,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: void BluetoothDeviceChromeOS::Connect(
BluetoothDevice::PairingDelegate* pairing_delegate,
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
if (num_connecting_calls_++ == 0)
adapter_->NotifyDeviceChanged(this);
VLOG(1) << object_path_.value() << ": Connecting, " << num_connecting_calls_
<< " in progress";
if (IsPaired() || !pairing_delegate || !IsPairable()) {
ConnectInternal(false, callback, error_callback);
} else {
DCHECK(!pairing_delegate_);
DCHECK(agent_.get() == NULL);
pairing_delegate_ = pairing_delegate;
pairing_delegate_used_ = false;
dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
agent_.reset(BluetoothAgentServiceProvider::Create(
system_bus, dbus::ObjectPath(kAgentPath), this));
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Registering agent for pairing";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
RegisterAgent(
dbus::ObjectPath(kAgentPath),
bluetooth_agent_manager::kKeyboardDisplayCapability,
base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgent,
weak_ptr_factory_.GetWeakPtr(),
callback,
error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgentError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
}
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::Connect(
BluetoothDevice::PairingDelegate* pairing_delegate,
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
if (num_connecting_calls_++ == 0)
adapter_->NotifyDeviceChanged(this);
VLOG(1) << object_path_.value() << ": Connecting, " << num_connecting_calls_
<< " in progress";
if (IsPaired() || !pairing_delegate || !IsPairable()) {
ConnectInternal(false, callback, error_callback);
} else {
DCHECK(!pairing_context_);
pairing_context_.reset(
new BluetoothAdapterChromeOS::PairingContext(pairing_delegate));
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
Pair(object_path_,
base::Bind(&BluetoothDeviceChromeOS::OnPair,
weak_ptr_factory_.GetWeakPtr(),
callback, error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnPairError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
}
| 171,221
|
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: on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476
|
on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
else if (handler->_is_dbus_handler != 1) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"cannot unregister internal handler"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_dbus_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
| 167,634
|
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: grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf,
struct grub_ext4_extent_header *ext_block,
grub_uint32_t fileblock)
{
struct grub_ext4_extent_idx *index;
while (1)
{
int i;
grub_disk_addr_t block;
index = (struct grub_ext4_extent_idx *) (ext_block + 1);
if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC)
return 0;
if (ext_block->depth == 0)
return ext_block;
for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++)
{
if (fileblock < grub_le_to_cpu32(index[i].block))
break;
}
if (--i < 0)
return 0;
block = grub_le_to_cpu16 (index[i].leaf_hi);
block = (block << 32) + grub_le_to_cpu32 (index[i].leaf);
if (grub_disk_read (data->disk,
block << LOG2_EXT2_BLOCK_SIZE (data),
0, EXT2_BLOCK_SIZE(data), buf))
return 0;
ext_block = (struct grub_ext4_extent_header *) buf;
}
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119
|
grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf,
struct grub_ext4_extent_header *ext_block,
grub_uint32_t fileblock)
{
struct grub_ext4_extent_idx *index;
while (1)
{
int i;
grub_disk_addr_t block;
index = (struct grub_ext4_extent_idx *) (ext_block + 1);
if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC)
return 0;
if (ext_block->depth == 0)
return ext_block;
for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++)
{
if (fileblock < grub_le_to_cpu32(index[i].block))
break;
}
if (--i < 0)
return 0;
block = grub_le_to_cpu16 (index[i].leaf_hi);
block = (block << 32) + grub_le_to_cpu32 (index[i].leaf);
if (grub_disk_read (data->disk,
block << LOG2_EXT2_BLOCK_SIZE (data),
0, EXT2_BLOCK_SIZE(data), buf)) {
return 0;
}
ext_block = (struct grub_ext4_extent_header *) buf;
}
}
| 168,088
|
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 RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
render_widget_host_view->AdjustSurfaceProtection();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
}
| 171,378
|
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 FrameView::updateLayoutAndStyleForPainting()
{
RefPtr<FrameView> protector(this);
updateLayoutAndStyleIfNeededRecursive();
if (RenderView* view = renderView()) {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get());
InspectorInstrumentation::willUpdateLayerTree(m_frame.get());
view->compositor()->updateIfNeededRecursive();
if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot())
m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded();
updateCompositedSelectionBoundsIfNeeded();
InspectorInstrumentation::didUpdateLayerTree(m_frame.get());
invalidateTreeIfNeededRecursive();
}
scrollContentsIfNeededRecursive();
ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean);
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
R=vollick@chromium.org
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416
|
void FrameView::updateLayoutAndStyleForPainting()
{
RefPtr<FrameView> protector(this);
updateLayoutAndStyleIfNeededRecursive();
updateWidgetPositionsIfNeeded();
if (RenderView* view = renderView()) {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get());
InspectorInstrumentation::willUpdateLayerTree(m_frame.get());
view->compositor()->updateIfNeededRecursive();
if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot())
m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded();
updateCompositedSelectionBoundsIfNeeded();
InspectorInstrumentation::didUpdateLayerTree(m_frame.get());
invalidateTreeIfNeededRecursive();
}
scrollContentsIfNeededRecursive();
ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean);
}
| 171,636
|
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 4x4 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,554
|
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: InternalWebIntentsDispatcherTest() {
replied_ = 0;
}
Commit Message: Fix uninitialized member in ctor.
TBR=darin@chromium.org
R=jhawkins@chromium.org
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/10377180
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137606 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
InternalWebIntentsDispatcherTest() {
InternalWebIntentsDispatcherTest()
: replied_(0),
notified_reply_type_(webkit_glue::WEB_INTENT_REPLY_INVALID) {
}
| 170,761
|
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 AcceleratedStaticBitmapImage::Abandon() {
texture_holder_->Abandon();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
void AcceleratedStaticBitmapImage::Abandon() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
texture_holder_->Abandon();
}
| 172,587
|
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: BackendImpl::BackendImpl(
const base::FilePath& path,
scoped_refptr<BackendCleanupTracker> cleanup_tracker,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: cleanup_tracker_(std::move(cleanup_tracker)),
background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <mmenke@chromium.org>
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
|
BackendImpl::BackendImpl(
const base::FilePath& path,
scoped_refptr<BackendCleanupTracker> cleanup_tracker,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: cleanup_tracker_(std::move(cleanup_tracker)),
background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
consider_evicting_at_op_end_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
| 172,696
|
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 bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)
{
BN_ULONG t1,t2;
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
mul_add_c(a[0],b[0],c1,c2,c3);
r[0]=c1;
c1=0;
mul_add_c(a[0],b[1],c2,c3,c1);
mul_add_c(a[1],b[0],c2,c3,c1);
r[1]=c2;
c2=0;
mul_add_c(a[2],b[0],c3,c1,c2);
mul_add_c(a[1],b[1],c3,c1,c2);
mul_add_c(a[0],b[2],c3,c1,c2);
r[2]=c3;
c3=0;
mul_add_c(a[0],b[3],c1,c2,c3);
mul_add_c(a[1],b[2],c1,c2,c3);
mul_add_c(a[2],b[1],c1,c2,c3);
mul_add_c(a[3],b[0],c1,c2,c3);
r[3]=c1;
c1=0;
mul_add_c(a[3],b[1],c2,c3,c1);
mul_add_c(a[2],b[2],c2,c3,c1);
mul_add_c(a[1],b[3],c2,c3,c1);
r[4]=c2;
c2=0;
mul_add_c(a[2],b[3],c3,c1,c2);
mul_add_c(a[3],b[2],c3,c1,c2);
r[5]=c3;
c3=0;
mul_add_c(a[3],b[3],c1,c2,c3);
r[6]=c1;
r[7]=c2;
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <emilia@openssl.org>
CWE ID: CWE-310
|
void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)
{
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
mul_add_c(a[0],b[0],c1,c2,c3);
r[0]=c1;
c1=0;
mul_add_c(a[0],b[1],c2,c3,c1);
mul_add_c(a[1],b[0],c2,c3,c1);
r[1]=c2;
c2=0;
mul_add_c(a[2],b[0],c3,c1,c2);
mul_add_c(a[1],b[1],c3,c1,c2);
mul_add_c(a[0],b[2],c3,c1,c2);
r[2]=c3;
c3=0;
mul_add_c(a[0],b[3],c1,c2,c3);
mul_add_c(a[1],b[2],c1,c2,c3);
mul_add_c(a[2],b[1],c1,c2,c3);
mul_add_c(a[3],b[0],c1,c2,c3);
r[3]=c1;
c1=0;
mul_add_c(a[3],b[1],c2,c3,c1);
mul_add_c(a[2],b[2],c2,c3,c1);
mul_add_c(a[1],b[3],c2,c3,c1);
r[4]=c2;
c2=0;
mul_add_c(a[2],b[3],c3,c1,c2);
mul_add_c(a[3],b[2],c3,c1,c2);
r[5]=c3;
c3=0;
mul_add_c(a[3],b[3],c1,c2,c3);
r[6]=c1;
r[7]=c2;
}
| 166,828
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-254
|
PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
| 165,312
|
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 RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
MaybeReattachToRenderFrame();
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
agent_ptr_.reset();
render_frame_alive_ = true;
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
session->SetRenderer(frame_host ? frame_host->GetProcess() : nullptr,
frame_host);
}
MaybeReattachToRenderFrame();
}
}
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 RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
MaybeReattachToRenderFrame();
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
agent_ptr_.reset();
render_frame_alive_ = true;
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1,
frame_host);
}
MaybeReattachToRenderFrame();
}
}
| 172,782
|
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 res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
Commit Message: Check partword is in range for # of partitions
and reformat tabs->spaces for readability.
Bug: 28556125
Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c
CWE ID: CWE-20
|
int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
| 173,562
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.time_page) {
kvm_release_page_dirty(vcpu->arch.time_page);
vcpu->arch.time_page = NULL;
}
}
Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>
CWE ID: CWE-399
|
static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
vcpu->arch.pv_time_enabled = false;
}
| 166,119
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
GROW;
return(ret);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
GROW;
return(ret);
}
| 171,309
|
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 PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
DCHECK(!defer_page_unload_);
defer_page_unload_ = true;
bool rv = false;
switch (event.GetType()) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
rv = OnMouseDown(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEUP:
rv = OnMouseUp(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
rv = OnMouseMove(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYDOWN:
rv = OnKeyDown(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYUP:
rv = OnKeyUp(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_CHAR:
rv = OnChar(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_TOUCHSTART: {
KillTouchTimer(next_touch_timer_id_);
pp::TouchInputEvent touch_event(event);
if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1)
ScheduleTouchTimer(touch_event);
break;
}
case PP_INPUTEVENT_TYPE_TOUCHEND:
KillTouchTimer(next_touch_timer_id_);
break;
case PP_INPUTEVENT_TYPE_TOUCHMOVE:
KillTouchTimer(next_touch_timer_id_);
default:
break;
}
DCHECK(defer_page_unload_);
defer_page_unload_ = false;
for (int page_index : deferred_page_unloads_)
pages_[page_index]->Unload();
deferred_page_unloads_.clear();
return rv;
}
Commit Message: [pdf] Use a temporary list when unloading pages
When traversing the |deferred_page_unloads_| list and handling the
unloads it's possible for new pages to get added to the list which will
invalidate the iterator.
This CL swaps the list with an empty list and does the iteration on the
list copy. New items that are unloaded while handling the defers will be
unloaded at a later point.
Bug: 780450
Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac
Reviewed-on: https://chromium-review.googlesource.com/758916
Commit-Queue: dsinclair <dsinclair@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Cr-Commit-Position: refs/heads/master@{#515056}
CWE ID: CWE-416
|
bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
DCHECK(!defer_page_unload_);
defer_page_unload_ = true;
bool rv = false;
switch (event.GetType()) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
rv = OnMouseDown(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEUP:
rv = OnMouseUp(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
rv = OnMouseMove(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYDOWN:
rv = OnKeyDown(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYUP:
rv = OnKeyUp(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_CHAR:
rv = OnChar(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_TOUCHSTART: {
KillTouchTimer(next_touch_timer_id_);
pp::TouchInputEvent touch_event(event);
if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1)
ScheduleTouchTimer(touch_event);
break;
}
case PP_INPUTEVENT_TYPE_TOUCHEND:
KillTouchTimer(next_touch_timer_id_);
break;
case PP_INPUTEVENT_TYPE_TOUCHMOVE:
KillTouchTimer(next_touch_timer_id_);
default:
break;
}
DCHECK(defer_page_unload_);
defer_page_unload_ = false;
// Store the pages to unload away because the act of unloading pages can cause
// there to be more pages to unload. We leave those extra pages to be unloaded
// on the next go around.
std::vector<int> pages_to_unload;
std::swap(pages_to_unload, deferred_page_unloads_);
for (int page_index : pages_to_unload)
pages_[page_index]->Unload();
return rv;
}
| 172,665
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416
|
PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
| 164,973
|
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: SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad,
SplashColorMode modeA, GBool alphaA,
GBool topDown) {
width = widthA;
height = heightA;
mode = modeA;
switch (mode) {
case splashModeMono1:
rowSize = (width + 7) >> 3;
break;
case splashModeMono8:
rowSize = width;
break;
case splashModeRGB8:
case splashModeBGR8:
rowSize = width * 3;
break;
case splashModeXBGR8:
rowSize = width * 4;
break;
#if SPLASH_CMYK
case splashModeCMYK8:
rowSize = width * 4;
break;
#endif
}
rowSize += rowPad - 1;
rowSize -= rowSize % rowPad;
data = (SplashColorPtr)gmalloc(rowSize * height);
if (!topDown) {
data += (height - 1) * rowSize;
rowSize = -rowSize;
}
if (alphaA) {
alpha = (Guchar *)gmalloc(width * height);
} else {
alpha = NULL;
}
}
Commit Message:
CWE ID: CWE-189
|
SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad,
SplashColorMode modeA, GBool alphaA,
GBool topDown) {
width = widthA;
height = heightA;
mode = modeA;
switch (mode) {
case splashModeMono1:
rowSize = (width + 7) >> 3;
break;
case splashModeMono8:
rowSize = width;
break;
case splashModeRGB8:
case splashModeBGR8:
rowSize = width * 3;
break;
case splashModeXBGR8:
rowSize = width * 4;
break;
#if SPLASH_CMYK
case splashModeCMYK8:
rowSize = width * 4;
break;
#endif
}
rowSize += rowPad - 1;
rowSize -= rowSize % rowPad;
data = (SplashColorPtr)gmallocn(rowSize, height);
if (!topDown) {
data += (height - 1) * rowSize;
rowSize = -rowSize;
}
if (alphaA) {
alpha = (Guchar *)gmallocn(width, height);
} else {
alpha = NULL;
}
}
| 164,620
|
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: swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
horAcc32(tif, cp0, cc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
return horAcc32(tif, cp0, cc);
}
| 166,889
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int ohci_bus_start(OHCIState *ohci)
{
ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
ohci_frame_boundary,
ohci);
if (ohci->eof_timer == NULL) {
trace_usb_ohci_bus_eof_timer_failed(ohci->name);
ohci_die(ohci);
return 0;
}
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
if (ohci->eof_timer == NULL) {
trace_usb_ohci_bus_eof_timer_failed(ohci->name);
ohci_die(ohci);
return 0;
}
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
static void ohci_bus_stop(OHCIState *ohci)
{
trace_usb_ohci_stop(ohci->name);
if (ohci->eof_timer) {
timer_del(ohci->eof_timer);
timer_free(ohci->eof_timer);
}
ohci->eof_timer = NULL;
}
/* Sets a flag in a port status register but only set it if the port is
}
Commit Message:
CWE ID:
|
static int ohci_bus_start(OHCIState *ohci)
{
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
if (ohci->eof_timer == NULL) {
trace_usb_ohci_bus_eof_timer_failed(ohci->name);
ohci_die(ohci);
return 0;
}
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
static void ohci_bus_stop(OHCIState *ohci)
{
trace_usb_ohci_stop(ohci->name);
timer_del(ohci->eof_timer);
}
/* Sets a flag in a port status register but only set it if the port is
}
| 165,188
|
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 ssl3_take_mac(SSL *s)
{
const char *sender;
int slen;
if (s->state & SSL_ST_CONNECT)
{
sender=s->method->ssl3_enc->server_finished_label;
sender=s->method->ssl3_enc->client_finished_label;
slen=s->method->ssl3_enc->client_finished_label_len;
}
s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
sender,slen,s->s3->tmp.peer_finish_md);
}
Commit Message:
CWE ID: CWE-20
|
static void ssl3_take_mac(SSL *s)
{
const char *sender;
int slen;
/* If no new cipher setup return immediately: other functions will
* set the appropriate error.
*/
if (s->s3->tmp.new_cipher == NULL)
return;
if (s->state & SSL_ST_CONNECT)
{
sender=s->method->ssl3_enc->server_finished_label;
sender=s->method->ssl3_enc->client_finished_label;
slen=s->method->ssl3_enc->client_finished_label_len;
}
s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
sender,slen,s->s3->tmp.peer_finish_md);
}
| 165,360
|
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 XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
m_exceptionCode = AbortError;
abortError();
return;
}
if (error.isTimeout()) {
didTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
m_exceptionCode = NetworkError;
networkError();
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
handleDidCancel();
return;
}
if (error.isTimeout()) {
handleDidTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
handleNetworkError();
}
| 171,165
|
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 *hashtable_get(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return pair->value;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
|
void *hashtable_get(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return pair->value;
}
| 166,530
|
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 ServiceWorkerContextCore::OnReportConsoleMessage(
ServiceWorkerVersion* version,
blink::mojom::ConsoleMessageSource source,
blink::mojom::ConsoleMessageLevel message_level,
const base::string16& message,
int line_number,
const GURL& source_url) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
const bool is_builtin_component = HasWebUIScheme(source_url);
LogConsoleMessage(ConsoleMessageLevelToLogSeverity(message_level), message,
line_number, is_builtin_component, wrapper_->is_incognito(),
base::UTF8ToUTF16(source_url.spec()));
observer_list_->Notify(
FROM_HERE, &ServiceWorkerContextCoreObserver::OnReportConsoleMessage,
version->version_id(),
ConsoleMessage(source, message_level, message, line_number, source_url));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <lowell@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
|
void ServiceWorkerContextCore::OnReportConsoleMessage(
ServiceWorkerVersion* version,
blink::mojom::ConsoleMessageSource source,
blink::mojom::ConsoleMessageLevel message_level,
const base::string16& message,
int line_number,
const GURL& source_url) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// RenderFrameHostImpl::DidAddMessageToConsole, which also asks the
const bool is_builtin_component = HasWebUIScheme(source_url);
LogConsoleMessage(ConsoleMessageLevelToLogSeverity(message_level), message,
line_number, is_builtin_component, wrapper_->is_incognito(),
base::UTF8ToUTF16(source_url.spec()));
observer_list_->Notify(
FROM_HERE, &ServiceWorkerContextCoreObserver::OnReportConsoleMessage,
version->version_id(),
ConsoleMessage(source, message_level, message, line_number, source_url));
}
| 172,487
|
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 OMXNodeInstance::setParameter(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
OMX_ERRORTYPE err = OMX_SetParameter(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::setParameter(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_SetParameter(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
| 174,139
|
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: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n-- && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
c = toupper_m(c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
Commit Message:
CWE ID: CWE-200
|
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
n -= c_size;
c = toupper_m(c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
| 164,669
|
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 rpc_type_of_NPPVariable(int variable)
{
int type;
switch (variable) {
case NPPVpluginNameString:
case NPPVpluginDescriptionString:
case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000
type = RPC_TYPE_STRING;
break;
case NPPVpluginWindowSize:
case NPPVpluginTimerInterval:
type = RPC_TYPE_INT32;
break;
case NPPVpluginNeedsXEmbed:
case NPPVpluginWindowBool:
case NPPVpluginTransparentBool:
case NPPVjavascriptPushCallerBool:
case NPPVpluginKeepLibraryInMemory:
type = RPC_TYPE_BOOLEAN;
break;
case NPPVpluginScriptableNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264
|
int rpc_type_of_NPPVariable(int variable)
{
int type;
switch (variable) {
case NPPVpluginNameString:
case NPPVpluginDescriptionString:
case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000
case NPPVpluginNativeAccessibleAtkPlugId:
type = RPC_TYPE_STRING;
break;
case NPPVpluginWindowSize:
case NPPVpluginTimerInterval:
type = RPC_TYPE_INT32;
break;
case NPPVpluginNeedsXEmbed:
case NPPVpluginWindowBool:
case NPPVpluginTransparentBool:
case NPPVjavascriptPushCallerBool:
case NPPVpluginKeepLibraryInMemory:
case NPPVpluginUrlRequestsDisplayedBool:
case NPPVpluginWantsAllNetworkStreams:
case NPPVpluginCancelSrcStream:
case NPPVSupportsAdvancedKeyHandling:
type = RPC_TYPE_BOOLEAN;
break;
case NPPVpluginScriptableNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
| 165,863
|
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: WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate)
: delegate_(delegate),
state_(INITIALIZED),
waiting_(false),
callback_(NULL),
handshake_request_(new WebSocketHandshakeRequestHandler),
handshake_response_(new WebSocketHandshakeResponseHandler),
started_to_send_handshake_request_(false),
handshake_request_sent_(0),
response_cookies_save_index_(0),
send_frame_handler_(new WebSocketFrameHandler),
receive_frame_handler_(new WebSocketFrameHandler) {
}
Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob
Don't post SendPending if it is already posted.
BUG=89795
TEST=none
Review URL: http://codereview.chromium.org/7488007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate)
: delegate_(delegate),
state_(INITIALIZED),
waiting_(false),
callback_(NULL),
handshake_request_(new WebSocketHandshakeRequestHandler),
handshake_response_(new WebSocketHandshakeResponseHandler),
started_to_send_handshake_request_(false),
handshake_request_sent_(0),
response_cookies_save_index_(0),
send_frame_handler_(new WebSocketFrameHandler),
receive_frame_handler_(new WebSocketFrameHandler),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
}
| 170,308
|
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 PPB_Buffer_Proxy::OnMsgCreate(
PP_Instance instance,
uint32_t size,
HostResource* result_resource,
ppapi::proxy::SerializedHandle* result_shm_handle) {
result_shm_handle->set_null_shmem();
HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance);
if (!dispatcher)
return;
thunk::EnterResourceCreation enter(instance);
if (enter.failed())
return;
PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance,
size);
if (local_buffer_resource == 0)
return;
thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer(
local_buffer_resource, false);
if (trusted_buffer.failed())
return;
int local_fd;
if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK)
return;
result_resource->SetHostResource(instance, local_buffer_resource);
base::PlatformFile platform_file =
#if defined(OS_WIN)
reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd));
#elif defined(OS_POSIX)
local_fd;
#else
#error Not implemented.
#endif
result_shm_handle->set_shmem(
dispatcher->ShareHandleWithRemote(platform_file, false), size);
}
Commit Message: Add permission checks for PPB_Buffer.
BUG=116317
TEST=browser_tests
Review URL: https://chromiumcodereview.appspot.com/11446075
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171951 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PPB_Buffer_Proxy::OnMsgCreate(
PP_Instance instance,
uint32_t size,
HostResource* result_resource,
ppapi::proxy::SerializedHandle* result_shm_handle) {
result_shm_handle->set_null_shmem();
HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance);
if (!dispatcher)
return;
if (!dispatcher->permissions().HasPermission(ppapi::PERMISSION_DEV))
return;
thunk::EnterResourceCreation enter(instance);
if (enter.failed())
return;
PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance,
size);
if (local_buffer_resource == 0)
return;
thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer(
local_buffer_resource, false);
if (trusted_buffer.failed())
return;
int local_fd;
if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK)
return;
result_resource->SetHostResource(instance, local_buffer_resource);
base::PlatformFile platform_file =
#if defined(OS_WIN)
reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd));
#elif defined(OS_POSIX)
local_fd;
#else
#error Not implemented.
#endif
result_shm_handle->set_shmem(
dispatcher->ShareHandleWithRemote(platform_file, false), size);
}
| 171,341
|
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: NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame(
BrowserFrame* browser_frame,
BrowserView* browser_view) {
if (views::Widget::IsPureViews())
return new BrowserFrameViews(browser_frame, browser_view);
return new BrowserFrameGtk(browser_frame, browser_view);
}
Commit Message: Fixed brekage when PureViews are enable but Desktop is not
TBR=ben@chromium.org
BUG=none
TEST=chrome starts with --use-pure-views with touchui
Review URL: http://codereview.chromium.org/7210037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91197 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame(
BrowserFrame* browser_frame,
BrowserView* browser_view) {
if (views::Widget::IsPureViews() &&
views::ViewsDelegate::views_delegate->GetDefaultParentView())
return new BrowserFrameViews(browser_frame, browser_view);
return new BrowserFrameGtk(browser_frame, browser_view);
}
| 170,315
|
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 OnReadAllMetadata(
const SessionStore::SessionInfo& session_info,
SessionStore::FactoryCompletionCallback callback,
std::unique_ptr<ModelTypeStore> store,
std::unique_ptr<ModelTypeStore::RecordList> record_list,
const base::Optional<syncer::ModelError>& error,
std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
if (error) {
std::move(callback).Run(error, /*store=*/nullptr,
/*metadata_batch=*/nullptr);
return;
}
std::map<std::string, sync_pb::SessionSpecifics> initial_data;
for (ModelTypeStore::Record& record : *record_list) {
const std::string& storage_key = record.id;
SessionSpecifics specifics;
if (storage_key.empty() ||
!specifics.ParseFromString(std::move(record.value))) {
DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key;
continue;
}
initial_data[storage_key].Swap(&specifics);
}
auto session_store = std::make_unique<SessionStore>(
sessions_client_, session_info, std::move(store),
std::move(initial_data), metadata_batch->GetAllMetadata(),
restored_foreign_tab_callback_);
std::move(callback).Run(/*error=*/base::nullopt, std::move(session_store),
std::move(metadata_batch));
}
Commit Message: Add trace event to sync_sessions::OnReadAllMetadata()
It is likely a cause of janks on UI thread on Android.
Add a trace event to get metrics about the duration.
BUG=902203
Change-Id: I4c4e9c2a20790264b982007ea7ee88ddfa7b972c
Reviewed-on: https://chromium-review.googlesource.com/c/1319369
Reviewed-by: Mikel Astiz <mastiz@chromium.org>
Commit-Queue: ssid <ssid@chromium.org>
Cr-Commit-Position: refs/heads/master@{#606104}
CWE ID: CWE-20
|
void OnReadAllMetadata(
const SessionStore::SessionInfo& session_info,
SessionStore::FactoryCompletionCallback callback,
std::unique_ptr<ModelTypeStore> store,
std::unique_ptr<ModelTypeStore::RecordList> record_list,
const base::Optional<syncer::ModelError>& error,
std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
// Remove after fixing https://crbug.com/902203.
TRACE_EVENT0("browser", "FactoryImpl::OnReadAllMetadata");
if (error) {
std::move(callback).Run(error, /*store=*/nullptr,
/*metadata_batch=*/nullptr);
return;
}
std::map<std::string, sync_pb::SessionSpecifics> initial_data;
for (ModelTypeStore::Record& record : *record_list) {
const std::string& storage_key = record.id;
SessionSpecifics specifics;
if (storage_key.empty() ||
!specifics.ParseFromString(std::move(record.value))) {
DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key;
continue;
}
initial_data[storage_key].Swap(&specifics);
}
auto session_store = std::make_unique<SessionStore>(
sessions_client_, session_info, std::move(store),
std::move(initial_data), metadata_batch->GetAllMetadata(),
restored_foreign_tab_callback_);
std::move(callback).Run(/*error=*/base::nullopt, std::move(session_store),
std::move(metadata_batch));
}
| 172,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: ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
}
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
|
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
if (speech_synthesizer_) {
ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) |
SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction(
ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0);
}
}
| 170,401
|
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(
Segment* pSegment,
long idx,
long long element_start
/* long long element_size */ ) :
m_pSegment(pSegment),
m_element_start(element_start),
m_index(idx),
m_pos(element_start),
m_element_size(-1 /* element_size */ ),
m_timecode(-1),
m_entries(NULL),
m_entries_size(0),
m_entries_count(-1) //means "has not been parsed yet"
{
}
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
|
Cluster::Cluster(
| 174,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: void RenderWidgetHostViewAura::OnLostResources() {
image_transport_clients_.clear();
current_surface_ = 0;
protection_state_id_ = 0;
current_surface_is_protected_ = true;
current_surface_in_use_by_compositor_ = true;
surface_route_id_ = 0;
UpdateExternalTexture();
locks_pending_commit_.clear();
DCHECK(!shared_surface_handle_.is_null());
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
factory->DestroySharedSurfaceHandle(shared_surface_handle_);
shared_surface_handle_ = factory->CreateSharedSurfaceHandle();
host_->CompositingSurfaceUpdated();
host_->ScheduleComposite();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAura::OnLostResources() {
image_transport_clients_.clear();
current_surface_ = 0;
UpdateExternalTexture();
locks_pending_commit_.clear();
DCHECK(!shared_surface_handle_.is_null());
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
factory->DestroySharedSurfaceHandle(shared_surface_handle_);
shared_surface_handle_ = factory->CreateSharedSurfaceHandle();
host_->CompositingSurfaceUpdated();
host_->ScheduleComposite();
}
| 171,381
|
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 put_filp(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
security_file_free(file);
file_sb_list_del(file);
file_free(file);
}
}
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 put_filp(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
security_file_free(file);
file_free(file);
}
}
| 166,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: native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
Commit Message: Verify that the native handle was created
The inputs to native_handle_create can cause an overflowed allocation,
so check the return value of native_handle_create before accessing
the memory it returns.
Bug:19334482
Change-Id: I1f489382776c2a1390793a79dc27ea17baa9b2a2
(cherry picked from commit eaac99a7172da52a76ba48c26413778a74951b1a)
CWE ID: CWE-189
|
native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
| 173,373
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
if (pWTIntFrame->numSamples < 0) {
ALOGE("b/26366256");
pWTIntFrame->numSamples = 0;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119
|
EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
if (pWTIntFrame->numSamples < 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
pWTIntFrame->numSamples = 0;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
| 174,607
|
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 PageHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (host_ == frame_host)
return;
RenderWidgetHostImpl* widget_host =
host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Remove(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
host_ = frame_host;
widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Add(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
}
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 PageHandler::SetRenderer(RenderProcessHost* process_host,
void PageHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
if (host_ == frame_host)
return;
RenderWidgetHostImpl* widget_host =
host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Remove(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
host_ = frame_host;
widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Add(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
}
| 172,764
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
Commit Message:
CWE ID: CWE-20
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%d' if more than one page should be extracted", destFileName);
return false;
}
// destFileName can have multiple %% and one %d
// We use auxDestFileName to replace all the valid % appearances
// by 'A' (random char that is not %), if at the end of replacing
// any of the valid appearances there is still any % around, the
// pattern is wrong
char *auxDestFileName = strdup(destFileName);
// %% can appear as many times as you want
char *p = strstr(auxDestFileName, "%%");
while (p != NULL) {
*p = 'A';
*(p + 1) = 'A';
p = strstr(p, "%%");
}
// %d can appear only one time
p = strstr(auxDestFileName, "%d");
if (p != NULL) {
*p = 'A';
}
// at this point any other % is wrong
p = strstr(auxDestFileName, "%");
if (p != NULL) {
error(errSyntaxError, -1, "'{0:s}' can only contain one '%d' pattern", destFileName);
free(auxDestFileName);
return false;
}
free(auxDestFileName);
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
| 164,653
|
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: PersistentHistogramAllocator::GetCreateHistogramResultHistogram() {
constexpr subtle::AtomicWord kHistogramUnderConstruction = 1;
static subtle::AtomicWord atomic_histogram_pointer = 0;
subtle::AtomicWord histogram_value =
subtle::Acquire_Load(&atomic_histogram_pointer);
if (histogram_value == kHistogramUnderConstruction)
return nullptr;
if (histogram_value)
return reinterpret_cast<HistogramBase*>(histogram_value);
if (subtle::NoBarrier_CompareAndSwap(&atomic_histogram_pointer, 0,
kHistogramUnderConstruction) != 0) {
return nullptr;
}
if (GlobalHistogramAllocator::Get()) {
DVLOG(1) << "Creating the results-histogram inside persistent"
<< " memory can cause future allocations to crash if"
<< " that memory is ever released (for testing).";
}
HistogramBase* histogram_pointer = LinearHistogram::FactoryGet(
kResultHistogram, 1, CREATE_HISTOGRAM_MAX, CREATE_HISTOGRAM_MAX + 1,
HistogramBase::kUmaTargetedHistogramFlag);
subtle::Release_Store(
&atomic_histogram_pointer,
reinterpret_cast<subtle::AtomicWord>(histogram_pointer));
return histogram_pointer;
}
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
|
PersistentHistogramAllocator::GetCreateHistogramResultHistogram() {
| 172,133
|
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: PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
bool was_preconnected)
: origin(origin),
was_preconnected(was_preconnected) {}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
PreconnectedRequestStats::PreconnectedRequestStats(const url::Origin& origin,
bool was_preconnected)
| 172,375
|
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 CrosLibrary::TestApi::SetSystemLibrary(
SystemLibrary* library, bool own) {
library_->system_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetSystemLibrary(
| 170,647
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
Commit Message:
CWE ID: CWE-189
|
static int rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
return USB_RET_STALL;
}
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
| 165,185
|
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 EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
size_t length = kRawDataSize / algorithm_.bytes_per_channel();
switch (algorithm_.bytes_per_channel()) {
case 4:
WriteFakeData<int32>(audio_data.get(), length);
break;
case 2:
WriteFakeData<int16>(audio_data.get(), length);
break;
case 1:
WriteFakeData<uint8>(audio_data.get(), length);
break;
default:
NOTREACHED() << "Unsupported audio bit depth in crossfade.";
}
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
// The value of the data is meaningless; we just want non-zero data to
// differentiate it from muted data.
memset(audio_data.get(), 1, kRawDataSize);
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
| 171,532
|
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: set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
PNG_CONST char *name)
{
/* Do this first so that the modifier fields are cleared even if an error
* happens allocating the png_struct. No allocation is done here so no
* cleanup is required.
*/
pm->state = modifier_start;
pm->bit_depth = 0;
pm->colour_type = 255;
pm->pending_len = 0;
pm->pending_chunk = 0;
pm->flush = 0;
pm->buffer_count = 0;
pm->buffer_position = 0;
return set_store_for_read(&pm->this, ppi, id, name);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
const char *name)
{
/* Do this first so that the modifier fields are cleared even if an error
* happens allocating the png_struct. No allocation is done here so no
* cleanup is required.
*/
pm->state = modifier_start;
pm->bit_depth = 0;
pm->colour_type = 255;
pm->pending_len = 0;
pm->pending_chunk = 0;
pm->flush = 0;
pm->buffer_count = 0;
pm->buffer_position = 0;
return set_store_for_read(&pm->this, ppi, id, name);
}
| 173,694
|
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: RenderProcessImpl::RenderProcessImpl()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
FROM_HERE, base::TimeDelta::FromSeconds(5),
this, &RenderProcessImpl::ClearTransportDIBCache)),
transport_dib_next_sequence_number_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
if (GetModuleHandle(L"LPK.DLL") == NULL) {
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
webkit_glue::SetJavaScriptFlags(
"--debugger-auto-break"
" --prof --prof-lazy");
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValueASCII(switches::kJavaScriptFlags));
}
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
RenderProcessImpl::RenderProcessImpl()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
FROM_HERE, base::TimeDelta::FromSeconds(5),
this, &RenderProcessImpl::ClearTransportDIBCache)),
transport_dib_next_sequence_number_(0),
enabled_bindings_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
if (GetModuleHandle(L"LPK.DLL") == NULL) {
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
webkit_glue::SetJavaScriptFlags(
"--debugger-auto-break"
" --prof --prof-lazy");
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValueASCII(switches::kJavaScriptFlags));
}
}
| 171,017
|
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: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos > ss * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos, ss * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
Commit Message: Fix bounds checks again.
CWE ID: CWE-119
|
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
| 165,624
|
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: pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
int littleendian)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) <<
(littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (littleendian)
{
if (fromIndex > 0) sourceByte >>= fromIndex;
if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
}
else
{
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
}
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
| 173,685
|
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 filter_average_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
uint8_t tmp[64 * 64];
assert(output_width <= 64);
assert(output_height <= 64);
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64,
output_width, output_height);
block2d_average_c(tmp, 64, dst_ptr, dst_stride,
output_width, output_height);
}
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 filter_average_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
uint8_t tmp[kMaxDimension * kMaxDimension];
assert(output_width <= kMaxDimension);
assert(output_height <= kMaxDimension);
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64,
output_width, output_height);
block2d_average_c(tmp, 64, dst_ptr, dst_stride,
output_width, output_height);
}
| 174,508
|
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 BrowserViewRenderer::DidOverscroll(gfx::Vector2dF accumulated_overscroll,
gfx::Vector2dF latest_overscroll_delta,
gfx::Vector2dF current_fling_velocity) {
const float physical_pixel_scale = dip_scale_ * page_scale_factor_;
if (accumulated_overscroll == latest_overscroll_delta)
overscroll_rounding_error_ = gfx::Vector2dF();
gfx::Vector2dF scaled_overscroll_delta =
gfx::ScaleVector2d(latest_overscroll_delta, physical_pixel_scale);
gfx::Vector2d rounded_overscroll_delta = gfx::ToRoundedVector2d(
scaled_overscroll_delta + overscroll_rounding_error_);
overscroll_rounding_error_ =
scaled_overscroll_delta - rounded_overscroll_delta;
gfx::Vector2dF fling_velocity_pixels =
gfx::ScaleVector2d(current_fling_velocity, physical_pixel_scale);
client_->DidOverscroll(rounded_overscroll_delta, fling_velocity_pixels);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void BrowserViewRenderer::DidOverscroll(gfx::Vector2dF accumulated_overscroll,
void BrowserViewRenderer::DidOverscroll(
const gfx::Vector2dF& accumulated_overscroll,
const gfx::Vector2dF& latest_overscroll_delta,
const gfx::Vector2dF& current_fling_velocity) {
const float physical_pixel_scale = dip_scale_ * page_scale_factor_;
if (accumulated_overscroll == latest_overscroll_delta)
overscroll_rounding_error_ = gfx::Vector2dF();
gfx::Vector2dF scaled_overscroll_delta =
gfx::ScaleVector2d(latest_overscroll_delta, physical_pixel_scale);
gfx::Vector2d rounded_overscroll_delta = gfx::ToRoundedVector2d(
scaled_overscroll_delta + overscroll_rounding_error_);
overscroll_rounding_error_ =
scaled_overscroll_delta - rounded_overscroll_delta;
gfx::Vector2dF fling_velocity_pixels =
gfx::ScaleVector2d(current_fling_velocity, physical_pixel_scale);
client_->DidOverscroll(rounded_overscroll_delta, fling_velocity_pixels);
}
| 171,613
|
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: ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,798
|
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 __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
skb = tcp_get_timestamping_opt_stats(sk);
else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype);
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <zzoru007@gmail.com>
Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: Willem de Bruijn <willemb@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-125
|
void __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly, opt_stats = false;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
skb = tcp_get_timestamping_opt_stats(sk);
opt_stats = true;
} else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
}
| 170,072
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AXLayoutObject::supportsARIADragging() const {
const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
return equalIgnoringCase(grabbed, "true") ||
equalIgnoringCase(grabbed, "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 AXLayoutObject::supportsARIADragging() const {
const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
return equalIgnoringASCIICase(grabbed, "true") ||
equalIgnoringASCIICase(grabbed, "false");
}
| 171,906
|
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: pch_write_line (lin line, FILE *file)
{
bool after_newline = p_line[line][p_len[line] - 1] == '\n';
if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file))
write_fatal ();
return after_newline;
}
Commit Message:
CWE ID: CWE-119
|
pch_write_line (lin line, FILE *file)
{
bool after_newline = (p_len[line] > 0) && (p_line[line][p_len[line] - 1] == '\n');
if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file))
write_fatal ();
return after_newline;
}
| 165,473
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const BlockEntry* Cues::GetBlock(
const CuePoint* pCP,
const CuePoint::TrackPosition* pTP) const
{
if (pCP == NULL)
return NULL;
if (pTP == NULL)
return NULL;
return m_pSegment->GetBlock(*pCP, *pTP);
}
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 BlockEntry* Cues::GetBlock(
if (pTP == NULL)
return NULL;
return m_pSegment->GetBlock(*pCP, *pTP);
}
| 174,287
|
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 nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
nsc_encode_argb_to_aycocg(context, bmpdata, rowstride);
if (context->ChromaSubsamplingLevel)
{
nsc_encode_subsampling(context);
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
|
void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
if (!context || !bmpdata || (rowstride == 0))
return FALSE;
if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))
return FALSE;
if (context->ChromaSubsamplingLevel)
{
if (!nsc_encode_subsampling(context))
return FALSE;
}
return TRUE;
}
| 169,287
|
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: process(register int code, unsigned char** fill)
{
int incode;
static unsigned char firstchar;
if (code == clear) {
codesize = datasize + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
return 1;
}
if (oldcode == -1) {
*(*fill)++ = suffix[code];
firstchar = oldcode = code;
return 1;
}
if (code > avail) {
fprintf(stderr, "code %d too large for %d\n", code, avail);
return 0;
}
incode = code;
if (code == avail) { /* the first code is always < avail */
*stackp++ = firstchar;
code = oldcode;
}
while (code > clear) {
*stackp++ = suffix[code];
code = prefix[code];
}
*stackp++ = firstchar = suffix[code];
prefix[avail] = oldcode;
suffix[avail] = firstchar;
avail++;
if (((avail & codemask) == 0) && (avail < 4096)) {
codesize++;
codemask += avail;
}
oldcode = incode;
do {
*(*fill)++ = *--stackp;
} while (stackp > stack);
return 1;
}
Commit Message: fix possible OOB write in gif2tiff.c
CWE ID: CWE-119
|
process(register int code, unsigned char** fill)
{
int incode;
static unsigned char firstchar;
if (code == clear) {
codesize = datasize + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
return 1;
}
if (oldcode == -1) {
if (code >= clear) {
fprintf(stderr, "bad input: code=%d is larger than clear=%d\n",code, clear);
return 0;
}
*(*fill)++ = suffix[code];
firstchar = oldcode = code;
return 1;
}
if (code > avail) {
fprintf(stderr, "code %d too large for %d\n", code, avail);
return 0;
}
incode = code;
if (code == avail) { /* the first code is always < avail */
*stackp++ = firstchar;
code = oldcode;
}
while (code > clear) {
*stackp++ = suffix[code];
code = prefix[code];
}
*stackp++ = firstchar = suffix[code];
prefix[avail] = oldcode;
suffix[avail] = firstchar;
avail++;
if (((avail & codemask) == 0) && (avail < 4096)) {
codesize++;
codemask += avail;
}
oldcode = incode;
do {
*(*fill)++ = *--stackp;
} while (stackp > stack);
return 1;
}
| 166,011
|
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 Track::Info::CopyStr(char* Info::*str, Info& dst_) const
{
if (str == static_cast<char* Info::*>(NULL))
return -1;
char*& dst = dst_.*str;
if (dst) //should be NULL already
return -1;
const char* const src = this->*str;
if (src == NULL)
return 0;
const size_t len = strlen(src);
dst = new (std::nothrow) char[len+1];
if (dst == NULL)
return -1;
strcpy(dst, src);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const
if (src == NULL)
return 0;
const size_t len = strlen(src);
dst = new (std::nothrow) char[len + 1];
if (dst == NULL)
return -1;
strcpy(dst, src);
return 0;
}
| 174,254
|
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 ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && (params.url.GetOrigin() != url_.GetOrigin())) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284
|
void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && !url::IsSameOriginWith(params.url, url_)) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
| 172,283
|
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: jbig2_sd_cat(Jbig2Ctx *ctx, int n_dicts, Jbig2SymbolDict **dicts)
{
int i, j, k, symbols;
Jbig2SymbolDict *new = NULL;
/* count the imported symbols and allocate a new array */
symbols = 0;
for (i = 0; i < n_dicts; i++)
symbols += dicts[i]->n_symbols;
/* fill a new array with cloned glyph pointers */
new = jbig2_sd_new(ctx, symbols);
if (new != NULL) {
k = 0;
for (i = 0; i < n_dicts; i++)
for (j = 0; j < dicts[i]->n_symbols; j++)
new->glyphs[k++] = jbig2_image_clone(ctx, dicts[i]->glyphs[j]);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate new symbol dictionary");
}
return new;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_sd_cat(Jbig2Ctx *ctx, int n_dicts, Jbig2SymbolDict **dicts)
jbig2_sd_cat(Jbig2Ctx *ctx, uint32_t n_dicts, Jbig2SymbolDict **dicts)
{
uint32_t i, j, k, symbols;
Jbig2SymbolDict *new_dict = NULL;
/* count the imported symbols and allocate a new array */
symbols = 0;
for (i = 0; i < n_dicts; i++)
symbols += dicts[i]->n_symbols;
/* fill a new array with cloned glyph pointers */
new_dict = jbig2_sd_new(ctx, symbols);
if (new_dict != NULL) {
k = 0;
for (i = 0; i < n_dicts; i++)
for (j = 0; j < dicts[i]->n_symbols; j++)
new_dict->glyphs[k++] = jbig2_image_clone(ctx, dicts[i]->glyphs[j]);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate new symbol dictionary");
}
return new_dict;
}
| 165,499
|
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 PrintWebViewHelper::CheckForCancel() {
bool cancel = false;
Send(new PrintHostMsg_CheckForCancel(
routing_id(),
print_pages_params_->params.preview_ui_addr,
print_pages_params_->params.preview_request_id,
&cancel));
if (cancel)
notify_browser_of_print_failure_ = false;
return cancel;
}
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
|
bool PrintWebViewHelper::CheckForCancel() {
const PrintMsg_Print_Params& print_params = print_pages_params_->params;
bool cancel = false;
Send(new PrintHostMsg_CheckForCancel(routing_id(),
print_params.preview_ui_id,
print_params.preview_request_id,
&cancel));
if (cancel)
notify_browser_of_print_failure_ = false;
return cancel;
}
| 170,856
|
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 nfs4_close_state(struct path *path, struct nfs4_state *state, mode_t mode)
{
__nfs4_close(path, state, mode, 0);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
void nfs4_close_state(struct path *path, struct nfs4_state *state, mode_t mode)
void nfs4_close_state(struct path *path, struct nfs4_state *state, fmode_t fmode)
{
__nfs4_close(path, state, fmode, 0);
}
| 165,710
|
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::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringCase(liveRegion, "polite") ||
equalIgnoringCase(liveRegion, "assertive");
}
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::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringASCIICase(liveRegion, "polite") ||
equalIgnoringASCIICase(liveRegion, "assertive");
}
| 171,927
|
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 EC_GROUP_clear_free(EC_GROUP *group)
{
if (!group) return;
if (group->meth->group_clear_finish != 0)
group->meth->group_clear_finish(group);
else if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_POINT_clear_free(group->generator);
BN_clear_free(&group->order);
OPENSSL_cleanse(group, sizeof *group);
OPENSSL_free(group);
}
Commit Message:
CWE ID: CWE-320
|
void EC_GROUP_clear_free(EC_GROUP *group)
{
if (!group) return;
if (group->meth->group_clear_finish != 0)
group->meth->group_clear_finish(group);
else if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->mont_data)
BN_MONT_CTX_free(group->mont_data);
if (group->generator != NULL)
EC_POINT_clear_free(group->generator);
BN_clear_free(&group->order);
OPENSSL_cleanse(group, sizeof *group);
OPENSSL_free(group);
}
| 165,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: bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const {
if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument())
return false;
return GetDocument()->IsSecureTransitionTo(url);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285
|
bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const {
bool LocalFrame::ShouldReuseDefaultView(
const KURL& url,
const ContentSecurityPolicy* csp) const {
if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument())
return false;
// The Window object should only be re-used if it is same-origin.
// Since sandboxing turns the origin into an opaque origin it needs to also
// be considered when deciding whether to reuse it.
// Spec:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
if (csp &&
SecurityContext::IsSandboxed(kSandboxOrigin, csp->GetSandboxMask())) {
return false;
}
return GetDocument()->IsSecureTransitionTo(url);
}
| 173,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: Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
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
|
Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,777
|
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 translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
struct iovec iov[], int iov_size)
{
const struct vhost_memory_region *reg;
struct vhost_memory *mem;
struct iovec *_iov;
u64 s = 0;
int ret = 0;
rcu_read_lock();
mem = rcu_dereference(dev->memory);
while ((u64)len > s) {
u64 size;
if (unlikely(ret >= iov_size)) {
ret = -ENOBUFS;
break;
}
reg = find_region(mem, addr, len);
if (unlikely(!reg)) {
ret = -EFAULT;
break;
}
_iov = iov + ret;
size = reg->memory_size - addr + reg->guest_phys_addr;
_iov->iov_len = min((u64)len, size);
_iov->iov_base = (void __user *)(unsigned long)
(reg->userspace_addr + addr - reg->guest_phys_addr);
s += size;
addr += size;
++ret;
}
rcu_read_unlock();
return ret;
}
Commit Message: vhost: fix length for cross region descriptor
If a single descriptor crosses a region, the
second chunk length should be decremented
by size translated so far, instead it includes
the full descriptor length.
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
Acked-by: Jason Wang <jasowang@redhat.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
struct iovec iov[], int iov_size)
{
const struct vhost_memory_region *reg;
struct vhost_memory *mem;
struct iovec *_iov;
u64 s = 0;
int ret = 0;
rcu_read_lock();
mem = rcu_dereference(dev->memory);
while ((u64)len > s) {
u64 size;
if (unlikely(ret >= iov_size)) {
ret = -ENOBUFS;
break;
}
reg = find_region(mem, addr, len);
if (unlikely(!reg)) {
ret = -EFAULT;
break;
}
_iov = iov + ret;
size = reg->memory_size - addr + reg->guest_phys_addr;
_iov->iov_len = min((u64)len - s, size);
_iov->iov_base = (void __user *)(unsigned long)
(reg->userspace_addr + addr - reg->guest_phys_addr);
s += size;
addr += size;
++ret;
}
rcu_read_unlock();
return ret;
}
| 166,142
|
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 gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = (r->glyph_data.bits.size - r->pos < n ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
Commit Message:
CWE ID: CWE-125
|
static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = ((r->pos >= r->glyph_data.bits.size ||
r->glyph_data.bits.size - r->pos < n) ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
| 164,779
|
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: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: saml2md::DynamicMetadataProvider(e),
m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
m_encoded(true), m_trust(nullptr)
{
const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
if (child && child->hasChildNodes()) {
auto_ptr_char s(child->getFirstChild()->getNodeValue());
if (s.get() && *s.get()) {
m_subst = s.get();
m_encoded = XMLHelper::getAttrBool(child, true, encoded);
m_hashed = XMLHelper::getAttrString(child, nullptr, hashed);
}
}
if (m_subst.empty()) {
child = XMLHelper::getFirstChildElement(e, Regex);
if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
m_match = XMLHelper::getAttrString(child, nullptr, match);
auto_ptr_char repl(child->getFirstChild()->getNodeValue());
if (repl.get() && *repl.get())
m_regex = repl.get();
}
}
if (!m_ignoreTransport) {
child = XMLHelper::getFirstChildElement(e, _TrustEngine);
string t = XMLHelper::getAttrString(child, nullptr, _type);
if (!t.empty()) {
TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
if (!dynamic_cast<X509TrustEngine*>(trust)) {
delete trust;
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
}
m_trust.reset(dynamic_cast<X509TrustEngine*>(trust));
m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr));
}
if (!m_trust.get() || !m_dummyCR.get())
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
}
}
Commit Message:
CWE ID: CWE-347
|
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: saml2md::DynamicMetadataProvider(e), MetadataProvider(e),
m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
m_encoded(true), m_trust(nullptr)
{
const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
if (child && child->hasChildNodes()) {
auto_ptr_char s(child->getFirstChild()->getNodeValue());
if (s.get() && *s.get()) {
m_subst = s.get();
m_encoded = XMLHelper::getAttrBool(child, true, encoded);
m_hashed = XMLHelper::getAttrString(child, nullptr, hashed);
}
}
if (m_subst.empty()) {
child = XMLHelper::getFirstChildElement(e, Regex);
if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
m_match = XMLHelper::getAttrString(child, nullptr, match);
auto_ptr_char repl(child->getFirstChild()->getNodeValue());
if (repl.get() && *repl.get())
m_regex = repl.get();
}
}
if (!m_ignoreTransport) {
child = XMLHelper::getFirstChildElement(e, _TrustEngine);
string t = XMLHelper::getAttrString(child, nullptr, _type);
if (!t.empty()) {
TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
if (!dynamic_cast<X509TrustEngine*>(trust)) {
delete trust;
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
}
m_trust.reset(dynamic_cast<X509TrustEngine*>(trust));
m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr));
}
if (!m_trust.get() || !m_dummyCR.get())
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
}
}
| 164,623
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function)
{
int scriptId = function->ScriptId();
if (scriptId == v8::UnboundScript::kNoScriptId)
return v8::Null(m_isolate);
int lineNumber = function->GetScriptLineNumber();
int columnNumber = function->GetScriptColumnNumber();
if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound)
return v8::Null(m_isolate);
v8::Local<v8::Object> location = v8::Object::New(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!markAsInternal(context, location, V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79
|
v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function)
{
int scriptId = function->ScriptId();
if (scriptId == v8::UnboundScript::kNoScriptId)
return v8::Null(m_isolate);
int lineNumber = function->GetScriptLineNumber();
int columnNumber = function->GetScriptColumnNumber();
if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound)
return v8::Null(m_isolate);
v8::Local<v8::Object> location = v8::Object::New(m_isolate);
if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!markAsInternal(context, location, V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
| 172,065
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int sock_recv_all(int sock_fd, uint8_t* buf, int len)
{
int r = len;
int ret = -1;
while(r)
{
do ret = recv(sock_fd, buf, r, MSG_WAITALL);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d recv errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
r -= ret;
}
return len;
}
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 sock_recv_all(int sock_fd, uint8_t* buf, int len)
{
int r = len;
int ret = -1;
while(r)
{
do ret = TEMP_FAILURE_RETRY(recv(sock_fd, buf, r, MSG_WAITALL));
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d recv errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
r -= ret;
}
return len;
}
| 173,468
|
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 Erase(const std::string& addr) {
base::AutoLock lock(lock_);
map_.erase(addr);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void Erase(const std::string& addr) {
// Erases the entry for |preview_id|.
void Erase(int32 preview_id) {
base::AutoLock lock(lock_);
map_.erase(preview_id);
}
| 170,830
|
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: dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
Commit Message: A DWARF related section marked SHT_NOBITS (elf section type)
is an error in the elf object. Now detected.
dwarf_elf_access.c
CWE ID: CWE-476
|
dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
if (!data->d_buf) {
/* If NULL it means 'the section has no data'
according to libelf documentation.
No DWARF-related section should ever have
'no data'. Happens if a section type is
SHT_NOBITS and no section libdwarf
wants to look at should be SHT_NOBITS. */
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
| 168,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: CronTab::initRegexObject() {
if ( ! CronTab::regex.isInitialized() ) {
const char *errptr;
int erroffset;
MyString pattern( CRONTAB_PARAMETER_PATTERN ) ;
if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) {
MyString error = "CronTab: Failed to compile Regex - ";
error += pattern;
EXCEPT( const_cast<char*>(error.Value()));
}
}
}
Commit Message:
CWE ID: CWE-134
|
CronTab::initRegexObject() {
if ( ! CronTab::regex.isInitialized() ) {
const char *errptr;
int erroffset;
MyString pattern( CRONTAB_PARAMETER_PATTERN ) ;
if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) {
MyString error = "CronTab: Failed to compile Regex - ";
error += pattern;
EXCEPT( "%s", const_cast<char*>(error.Value()) );
}
}
}
| 165,383
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_expand_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_expand_16(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_expand_16_set(PNG_CONST image_transform *this,
image_transform_png_set_expand_16_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_expand_16(pp);
/* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
# if PNG_LIBPNG_VER < 10700
if (that->this.has_tRNS)
that->this.is_transparent = 1;
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,628
|
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: MediaStreamImpl::~MediaStreamImpl() {
DCHECK(!peer_connection_handler_);
if (dependency_factory_.get())
dependency_factory_->ReleasePeerConnectionFactory();
if (network_manager_) {
if (chrome_worker_thread_.IsRunning()) {
chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
&MediaStreamImpl::DeleteIpcNetworkManager,
base::Unretained(this)));
} else {
NOTREACHED() << "Worker thread not running.";
}
}
}
Commit Message: Explicitly stopping thread in MediaStreamImpl dtor to avoid any racing issues.
This may solve the below bugs.
BUG=112408,111202
TEST=content_unittests
Review URL: https://chromiumcodereview.appspot.com/9307058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120222 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
MediaStreamImpl::~MediaStreamImpl() {
DCHECK(!peer_connection_handler_);
if (dependency_factory_.get())
dependency_factory_->ReleasePeerConnectionFactory();
if (network_manager_) {
if (chrome_worker_thread_.IsRunning()) {
chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
&MediaStreamImpl::DeleteIpcNetworkManager,
base::Unretained(this)));
// Stopping the thread will wait until all tasks have been
// processed before returning. We wait for the above task to finish before
// letting the destructor continue to avoid any potential race issues.
chrome_worker_thread_.Stop();
} else {
NOTREACHED() << "Worker thread not running.";
}
}
}
| 170,957
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void ext4_end_io_work(struct work_struct *work)
{
ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
struct inode *inode = io->inode;
int ret = 0;
mutex_lock(&inode->i_mutex);
ret = ext4_end_io_nolock(io);
if (ret >= 0) {
if (!list_empty(&io->list))
list_del_init(&io->list);
ext4_free_io_end(io);
}
mutex_unlock(&inode->i_mutex);
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_end_io_work(struct work_struct *work)
{
ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
struct inode *inode = io->inode;
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned long flags;
int ret;
mutex_lock(&inode->i_mutex);
ret = ext4_end_io_nolock(io);
if (ret < 0) {
mutex_unlock(&inode->i_mutex);
return;
}
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
if (!list_empty(&io->list))
list_del_init(&io->list);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
mutex_unlock(&inode->i_mutex);
ext4_free_io_end(io);
}
| 167,542
|
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: BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mIsBackup(false),
mPortIndex(portIndex) {
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mCopyFromOmx(false),
mCopyToOmx(false),
mPortIndex(portIndex),
mBackup(NULL) {
}
| 174,125
|
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 ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const {
return url.SchemeIs(chrome::kChromeDevToolsScheme) ||
url.SchemeIs(chrome::kChromeInternalScheme) ||
url.SchemeIs(chrome::kChromeUIScheme);
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const {
| 171,008
|
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 Chapters::Edition* Chapters::GetEdition(int idx) const
{
if (idx < 0)
return NULL;
if (idx >= m_editions_count)
return NULL;
return m_editions + idx;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Chapters::Edition* Chapters::GetEdition(int idx) const
const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size;
Edition* const editions = new (std::nothrow) Edition[size];
if (editions == NULL)
return false;
for (int idx = 0; idx < m_editions_count; ++idx) {
m_editions[idx].ShallowCopy(editions[idx]);
}
delete[] m_editions;
m_editions = editions;
m_editions_size = size;
return true;
}
| 174,310
|
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 Track::Info::CopyStr(char* Info::*str, Info& dst_) const {
if (str == static_cast<char * Info::*>(NULL))
return -1;
char*& dst = dst_.*str;
if (dst) // should be NULL already
return -1;
const char* const src = this->*str;
if (src == NULL)
return 0;
const size_t len = strlen(src);
dst = new (std::nothrow) char[len + 1];
if (dst == NULL)
return -1;
strcpy(dst, src);
return 0;
}
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
|
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const {
if (str == static_cast<char * Info::*>(NULL))
return -1;
char*& dst = dst_.*str;
if (dst) // should be NULL already
return -1;
const char* const src = this->*str;
if (src == NULL)
return 0;
const size_t len = strlen(src);
dst = SafeArrayAlloc<char>(1, len + 1);
if (dst == NULL)
return -1;
strcpy(dst, src);
return 0;
}
| 173,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: zrestore(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
alloc_save_t *asave;
bool last;
vm_save_t *vmsave;
int code = restore_check_operand(op, &asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0
) {
osp++;
return code;
}
}
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
Commit Message:
CWE ID: CWE-78
|
zrestore(i_ctx_t *i_ctx_p)
restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave)
{
os_ptr op = osp;
int code = restore_check_operand(op, asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(*asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0
) {
osp++;
return code;
}
}
osp++;
return 0;
}
/* the semantics of restore differ slightly between Level 1 and
Level 2 and later - the latter includes restoring the device
state (whilst Level 1 didn't have "page devices" as such).
Hence we have two restore operators - one here (Level 1)
and one in zdevice2.c (Level 2+). For that reason, the
operand checking and guts of the restore operation are
separated so both implementations can use them to best
effect.
*/
int
dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave)
{
os_ptr op = osp;
bool last;
vm_save_t *vmsave;
int code;
osp--;
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
| 164,688
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
return 0;
}
Commit Message: Use XFixes to update the clipboard sequence number.
BUG=73478
TEST=manual testing
Review URL: http://codereview.chromium.org/8501002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109528 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
if (buffer == BUFFER_STANDARD)
return SelectionChangeObserver::GetInstance()->clipboard_sequence_number();
else
return SelectionChangeObserver::GetInstance()->primary_sequence_number();
}
| 170,962
|
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: BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <mmenke@chromium.org>
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
|
BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
consider_evicting_at_op_end_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
| 172,697
|
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: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
IncludePrivacySensitiveFields include_privacy_sensitive_fields) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
if (include_privacy_sensitive_fields == INCLUDE_PRIVACY_SENSITIVE_FIELDS) {
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
// Privacy-sensitive fields: these should be stripped off by
// ScrubTabValueForExtension if the extension should not see them.
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
| 171,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: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125
|
MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
| 169,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: std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
auto border = std::make_unique<views::BubbleBorder>(
views::BubbleBorder::NONE, views::BubbleBorder::SMALL_SHADOW,
SK_ColorWHITE);
border->SetCornerRadius(GetCornerRadius());
border->set_md_shadow_elevation(
ChromeLayoutProvider::Get()->GetShadowElevationMetric(
views::EMPHASIS_MEDIUM));
return border;
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <rkaplow@chromium.org>
Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org>
Reviewed-by: Fabio Tirelo <ftirelo@chromium.org>
Reviewed-by: Tommy Martino <tmartino@chromium.org>
Commit-Queue: Mathieu Perreault <mathp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416
|
std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
| 172,094
|
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: set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
Commit Message: Fix compile warning introduced in commit c6247a9
Commit c6247a9 - "Add command line and configuration option to set umask"
introduced a compile warning, although the code would have worked OK.
Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
CWE ID: CWE-200
|
set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return 0;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
| 170,158
|
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 ext4_xattr_destroy_cache(struct mb_cache *cache)
{
if (cache)
mb_cache_destroy(cache);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
void ext4_xattr_destroy_cache(struct mb_cache *cache)
void ext4_xattr_destroy_cache(struct mb2_cache *cache)
{
if (cache)
mb2_cache_destroy(cache);
}
| 169,994
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(imagetruecolortopalette)
{
zval *IM;
zend_bool dither;
long ncolors;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (ncolors <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero");
RETURN_FALSE;
}
gdImageTrueColorToPalette(im, dither, ncolors);
RETURN_TRUE;
}
Commit Message: Fix bug#72697 - select_colors write out-of-bounds
CWE ID: CWE-787
|
PHP_FUNCTION(imagetruecolortopalette)
{
zval *IM;
zend_bool dither;
long ncolors;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (ncolors <= 0 || ncolors > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX);
RETURN_FALSE;
}
gdImageTrueColorToPalette(im, dither, (int)ncolors);
RETURN_TRUE;
}
| 166,953
|
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 ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
switch (data_type) {
case syncable::SESSIONS:
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableSyncTabs)) {
return;
}
RegisterDataTypeController(
new browser_sync::SessionDataTypeController(factory_.get(),
profile_,
this));
return;
default:
break;
}
NOTREACHED();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
void ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
NOTREACHED();
}
| 170,788
|
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 UpdateProperty(const ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void UpdateProperty(const ImePropertyList& prop_list) {
void UpdateProperty(const input_method::ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
| 170,509
|
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: sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option)
{
ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option);
Mutex::Autolock lock(mLock);
Mutex::Autolock glock(sLock);
mThumbnail.clear();
if (mRetriever == NULL) {
ALOGE("retriever is not initialized");
return NULL;
}
VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option);
if (frame == NULL) {
ALOGE("failed to capture a video frame");
return NULL;
}
size_t size = sizeof(VideoFrame) + frame->mSize;
sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient");
if (heap == NULL) {
ALOGE("failed to create MemoryDealer");
delete frame;
return NULL;
}
mThumbnail = new MemoryBase(heap, 0, size);
if (mThumbnail == NULL) {
ALOGE("not enough memory for VideoFrame size=%u", size);
delete frame;
return NULL;
}
VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer());
frameCopy->mWidth = frame->mWidth;
frameCopy->mHeight = frame->mHeight;
frameCopy->mDisplayWidth = frame->mDisplayWidth;
frameCopy->mDisplayHeight = frame->mDisplayHeight;
frameCopy->mSize = frame->mSize;
frameCopy->mRotationAngle = frame->mRotationAngle;
ALOGV("rotation: %d", frameCopy->mRotationAngle);
frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame);
memcpy(frameCopy->mData, frame->mData, frame->mSize);
delete frame; // Fix memory leakage
return mThumbnail;
}
Commit Message: Clear unused pointer field when sending across binder
Bug: 28377502
Change-Id: Iad5ebfb0a9ef89f09755bb332579dbd3534f9c98
CWE ID: CWE-20
|
sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option)
{
ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option);
Mutex::Autolock lock(mLock);
Mutex::Autolock glock(sLock);
mThumbnail.clear();
if (mRetriever == NULL) {
ALOGE("retriever is not initialized");
return NULL;
}
VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option);
if (frame == NULL) {
ALOGE("failed to capture a video frame");
return NULL;
}
size_t size = sizeof(VideoFrame) + frame->mSize;
sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient");
if (heap == NULL) {
ALOGE("failed to create MemoryDealer");
delete frame;
return NULL;
}
mThumbnail = new MemoryBase(heap, 0, size);
if (mThumbnail == NULL) {
ALOGE("not enough memory for VideoFrame size=%u", size);
delete frame;
return NULL;
}
VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer());
frameCopy->mWidth = frame->mWidth;
frameCopy->mHeight = frame->mHeight;
frameCopy->mDisplayWidth = frame->mDisplayWidth;
frameCopy->mDisplayHeight = frame->mDisplayHeight;
frameCopy->mSize = frame->mSize;
frameCopy->mRotationAngle = frame->mRotationAngle;
ALOGV("rotation: %d", frameCopy->mRotationAngle);
frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame);
memcpy(frameCopy->mData, frame->mData, frame->mSize);
frameCopy->mData = 0;
delete frame; // Fix memory leakage
return mThumbnail;
}
| 173,550
|
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_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
{
*ret = x +1;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
| 165,105
|
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 RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
texture_layer_->setTextureId(params.surface_handle);
DCHECK(texture_layer_ == layer_);
layer_->setBounds(params.size);
texture_id_in_layer_ = params.surface_handle;
texture_size_in_layer_ = params.size;
DCHECK(!CompositorImpl::IsThreadingEnabled());
uint32 sync_point =
ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint();
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, true, sync_point);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
ImageTransportFactoryAndroid* factory =
ImageTransportFactoryAndroid::GetInstance();
// need to delay the ACK until after commit and use more than a single
// texture.
DCHECK(!CompositorImpl::IsThreadingEnabled());
uint64 previous_buffer = current_buffer_id_;
if (previous_buffer && texture_id_in_layer_) {
DCHECK(id_to_mailbox_.find(previous_buffer) != id_to_mailbox_.end());
ImageTransportFactoryAndroid::GetInstance()->ReleaseTexture(
texture_id_in_layer_,
reinterpret_cast<const signed char*>(
id_to_mailbox_[previous_buffer].c_str()));
}
current_buffer_id_ = params.surface_handle;
if (!texture_id_in_layer_) {
texture_id_in_layer_ = factory->CreateTexture();
texture_layer_->setTextureId(texture_id_in_layer_);
}
DCHECK(id_to_mailbox_.find(current_buffer_id_) != id_to_mailbox_.end());
ImageTransportFactoryAndroid::GetInstance()->AcquireTexture(
texture_id_in_layer_,
reinterpret_cast<const signed char*>(
id_to_mailbox_[current_buffer_id_].c_str()));
texture_layer_->setNeedsDisplay();
texture_layer_->setBounds(params.size);
texture_size_in_layer_ = params.size;
uint32 sync_point =
ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint();
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, previous_buffer, sync_point);
}
| 171,369
|
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 ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!iter->ReadData(&fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!iter->ReadData(&variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Commit-Queue: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125
|
bool ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
SkImageInfo image_info;
if (!ReadParam(m, iter, &image_info))
return false;
const char* bitmap_data;
int bitmap_data_size = 0;
if (!iter->ReadData(&bitmap_data, &bitmap_data_size))
return false;
// ReadData() only returns true if bitmap_data_size >= 0.
if (!r->tryAllocPixels(image_info))
return false;
if (static_cast<size_t>(bitmap_data_size) != r->computeByteSize())
return false;
memcpy(r->getPixels(), bitmap_data, bitmap_data_size);
return true;
}
| 172,894
|
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 ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
base::MakeUnique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <jbroman@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Bence Béky <bnc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311
|
void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
std::make_unique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
| 173,260
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.