instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
Commit Message: CVE-2017-13035/Properly handle IS-IS IDs shorter than a system ID (MAC address).
Some of them are variable-length, with a field giving the total length,
and therefore they can be shorter than 6 octets. If one is, don't run
past the end.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
int sysid_len;
sysid_len = SYSTEM_ID_LEN;
if (sysid_len > id_len)
sysid_len = id_len;
for (i = 1; i <= sysid_len; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
| 167,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int validation_muldiv(int count, int argc, char **argv)
{
int tested = 0;
int overflow = 0;
int error = 0;
int error64 = 0;
int passed = 0;
int randbits = 0;
png_uint_32 randbuffer;
png_fixed_point a;
png_int_32 times, div;
while (--argc > 0)
{
fprintf(stderr, "unknown argument %s\n", *++argv);
return 1;
}
/* Find out about the random number generator. */
randbuffer = RAND_MAX;
while (randbuffer != 0) ++randbits, randbuffer >>= 1;
printf("Using random number generator that makes %d bits\n", randbits);
for (div=0; div<32; div += randbits)
randbuffer = (randbuffer << randbits) ^ rand();
a = 0;
times = div = 0;
do
{
png_fixed_point result;
/* NOTE: your mileage may vary, a type is required below that can
* hold 64 bits or more, if floating point is used a 64 bit or
* better mantissa is required.
*/
long long int fp, fpround;
unsigned long hi, lo;
int ok;
/* Check the values, png_64bit_product can only handle positive
* numbers, so correct for that here.
*/
{
long u1, u2;
int n = 0;
if (a < 0) u1 = -a, n = 1; else u1 = a;
if (times < 0) u2 = -times, n = !n; else u2 = times;
png_64bit_product(u1, u2, &hi, &lo);
if (n)
{
/* -x = ~x+1 */
lo = ((~lo) + 1) & 0xffffffff;
hi = ~hi;
if (lo == 0) ++hi;
}
}
fp = a;
fp *= times;
if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
{
fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
a, times, hi, lo, fp);
++error64;
}
if (div != 0)
{
/* Round - this is C round to zero. */
if ((fp < 0) != (div < 0))
fp -= div/2;
else
fp += div/2;
fp /= div;
fpround = fp;
/* Assume 2's complement here: */
ok = fpround <= PNG_UINT_31_MAX &&
fpround >= -1-(long long int)PNG_UINT_31_MAX;
if (!ok) ++overflow;
}
else
ok = 0, ++overflow, fpround = fp/*misleading*/;
if (verbose)
fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n", a, times, div,
fp, ok ? "ok" : "overflow");
++tested;
if (png_muldiv(&result, a, times, div) != ok)
{
++error;
if (ok)
fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n", a,
times, div, fp);
else
fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n", a,
times, div, result, fp);
}
else if (ok && result != fpround)
{
++error;
fprintf(stderr, "%d * %d / %d -> %d not %lld\n", a, times, div, result,
fp);
}
else
++passed;
/* Generate three new values, this uses rand() and rand() only returns
* up to RAND_MAX.
*/
/* CRUDE */
a += times;
times += div;
div = randbuffer;
randbuffer = (randbuffer << randbits) ^ rand();
}
while (--count > 0);
printf("%d tests including %d overflows, %d passed, %d failed (%d 64 bit "
"errors)\n", tested, overflow, passed, error, error64);
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int validation_muldiv(int count, int argc, char **argv)
{
int tested = 0;
int overflow = 0;
int error = 0;
int error64 = 0;
int passed = 0;
int randbits = 0;
png_uint_32 randbuffer;
png_fixed_point a;
png_int_32 times, div;
while (--argc > 0)
{
fprintf(stderr, "unknown argument %s\n", *++argv);
return 1;
}
/* Find out about the random number generator. */
randbuffer = RAND_MAX;
while (randbuffer != 0) ++randbits, randbuffer >>= 1;
printf("Using random number generator that makes %d bits\n", randbits);
for (div=0; div<32; div += randbits)
randbuffer = (randbuffer << randbits) ^ rand();
a = 0;
times = div = 0;
do
{
png_fixed_point result;
/* NOTE: your mileage may vary, a type is required below that can
* hold 64 bits or more, if floating point is used a 64-bit or
* better mantissa is required.
*/
long long int fp, fpround;
unsigned long hi, lo;
int ok;
/* Check the values, png_64bit_product can only handle positive
* numbers, so correct for that here.
*/
{
long u1, u2;
int n = 0;
if (a < 0) u1 = -a, n = 1; else u1 = a;
if (times < 0) u2 = -times, n = !n; else u2 = times;
png_64bit_product(u1, u2, &hi, &lo);
if (n)
{
/* -x = ~x+1 */
lo = ((~lo) + 1) & 0xffffffff;
hi = ~hi;
if (lo == 0) ++hi;
}
}
fp = a;
fp *= times;
if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
{
fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
a, times, hi, lo, fp);
++error64;
}
if (div != 0)
{
/* Round - this is C round to zero. */
if ((fp < 0) != (div < 0))
fp -= div/2;
else
fp += div/2;
fp /= div;
fpround = fp;
/* Assume 2's complement here: */
ok = fpround <= PNG_UINT_31_MAX &&
fpround >= -1-(long long int)PNG_UINT_31_MAX;
if (!ok) ++overflow;
}
else
ok = 0, ++overflow, fpround = fp/*misleading*/;
if (verbose)
fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n", a, times, div,
fp, ok ? "ok" : "overflow");
++tested;
if (png_muldiv(&result, a, times, div) != ok)
{
++error;
if (ok)
fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n", a,
times, div, fp);
else
fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n", a,
times, div, result, fp);
}
else if (ok && result != fpround)
{
++error;
fprintf(stderr, "%d * %d / %d -> %d not %lld\n", a, times, div, result,
fp);
}
else
++passed;
/* Generate three new values, this uses rand() and rand() only returns
* up to RAND_MAX.
*/
/* CRUDE */
a += times;
times += div;
div = randbuffer;
randbuffer = (randbuffer << randbits) ^ rand();
}
while (--count > 0);
printf("%d tests including %d overflows, %d passed, %d failed (%d 64-bit "
"errors)\n", tested, overflow, passed, error, error64);
return 0;
}
| 173,721 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::Info::Info():
uid(0),
defaultDuration(0),
codecDelay(0),
seekPreRoll(0),
nameAsUTF8(NULL),
language(NULL),
codecId(NULL),
codecNameAsUTF8(NULL),
codecPrivate(NULL),
codecPrivateSize(0),
lacing(false)
{
}
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 | Track::Info::Info():
| 174,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool RenderMenuList::multiple()
{
return toHTMLSelectElement(node())->multiple();
}
Commit Message: PopupMenuClient::multiple() should be const
https://bugs.webkit.org/show_bug.cgi?id=76771
Patch by Benjamin Poulain <[email protected]> on 2012-01-21
Reviewed by Kent Tamura.
* platform/PopupMenuClient.h:
(WebCore::PopupMenuClient::multiple):
* rendering/RenderMenuList.cpp:
(WebCore::RenderMenuList::multiple):
* rendering/RenderMenuList.h:
git-svn-id: svn://svn.chromium.org/blink/trunk@105570 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | bool RenderMenuList::multiple()
bool RenderMenuList::multiple() const
{
return toHTMLSelectElement(node())->multiple();
}
| 170,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebGLRenderingContextBase::~WebGLRenderingContextBase() {
destruction_in_progress_ = true;
DestroyContext();
RestoreEvictedContext(this);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | WebGLRenderingContextBase::~WebGLRenderingContextBase() {
destruction_in_progress_ = true;
clearProgramCompletionQueries();
DestroyContext();
RestoreEvictedContext(this);
}
| 172,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
ND_TCHECK2(p[0], 3);
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_atm2]"));
return l2info.header_len;
}
| 167,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags = mrb_obj_ptr(self)->flags;
return clone;
}
Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036
Copying all flags from the original object may overwrite the clone's
flags e.g. the embedded flag.
CWE ID: CWE-476 | mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;
return clone;
}
| 169,202 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SoftAACEncoder::~SoftAACEncoder() {
delete[] mInputFrame;
mInputFrame = NULL;
if (mEncoderHandle) {
CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
mEncoderHandle = NULL;
}
delete mApiHandle;
mApiHandle = NULL;
delete mMemOperator;
mMemOperator = NULL;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | SoftAACEncoder::~SoftAACEncoder() {
onReset();
if (mEncoderHandle) {
CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
mEncoderHandle = NULL;
}
delete mApiHandle;
mApiHandle = NULL;
delete mMemOperator;
mMemOperator = NULL;
}
| 174,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt);
break;
case BPF_TYPE_MAP:
bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
raw = bpf_prog_inc(raw);
break;
case BPF_TYPE_MAP:
raw = bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
| 167,250 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GrabWindowSnapshot(gfx::NativeWindow window,
std::vector<unsigned char>* png_representation,
const gfx::Rect& snapshot_bounds) {
ui::Compositor* compositor = window->layer()->GetCompositor();
gfx::Rect read_pixels_bounds = snapshot_bounds;
read_pixels_bounds.set_origin(
snapshot_bounds.origin().Add(window->bounds().origin()));
gfx::Rect read_pixels_bounds_in_pixel =
ui::ConvertRectToPixel(window->layer(), read_pixels_bounds);
DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right());
DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom());
DCHECK_LE(0, read_pixels_bounds.x());
DCHECK_LE(0, read_pixels_bounds.y());
SkBitmap bitmap;
if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
return false;
unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels());
gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
read_pixels_bounds_in_pixel.size(),
bitmap.rowBytes(), true,
std::vector<gfx::PNGCodec::Comment>(),
png_representation);
return true;
}
Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS.
BUG=119492
TEST=manually done
Review URL: https://chromiumcodereview.appspot.com/10386124
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool GrabWindowSnapshot(gfx::NativeWindow window,
std::vector<unsigned char>* png_representation,
const gfx::Rect& snapshot_bounds) {
#if defined(OS_LINUX)
// We use XGetImage() for Linux/ChromeOS for performance reasons.
// See crbug.com/122720
if (window->GetRootWindow()->GrabSnapshot(
snapshot_bounds, png_representation))
return true;
#endif // OS_LINUX
ui::Compositor* compositor = window->layer()->GetCompositor();
gfx::Rect read_pixels_bounds = snapshot_bounds;
read_pixels_bounds.set_origin(
snapshot_bounds.origin().Add(window->bounds().origin()));
gfx::Rect read_pixels_bounds_in_pixel =
ui::ConvertRectToPixel(window->layer(), read_pixels_bounds);
DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right());
DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom());
DCHECK_LE(0, read_pixels_bounds.x());
DCHECK_LE(0, read_pixels_bounds.y());
SkBitmap bitmap;
if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
return false;
unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels());
gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
read_pixels_bounds_in_pixel.size(),
bitmap.rowBytes(), true,
std::vector<gfx::PNGCodec::Comment>(),
png_representation);
return true;
}
| 170,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (key->state == KEY_IS_UNINSTANTIATED) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
mark_key_instantiated(key, 0);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret;
}
| 167,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
Commit Message: (for 4.9.3) CVE-2018-14467/BGP: Fix BGP_CAPCODE_MP.
Add a bounds check and a comment to bgp_capabilities_print().
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 | bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
/* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */
ND_TCHECK_8BITS(opt + i + 5);
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
| 169,844 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() {
return delegated_frame_host_ ? delegated_frame_host_->GetFrameSinkId()
: cc::FrameSinkId();
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
[email protected]
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254 | cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() {
return frame_sink_id_;
}
| 172,234 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void perf_callchain_user_64(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long sp, next_sp;
unsigned long next_ip;
unsigned long lr;
long level = 0;
struct signal_frame_64 __user *sigframe;
unsigned long __user *fp, *uregs;
next_ip = perf_instruction_pointer(regs);
lr = regs->link;
sp = regs->gpr[1];
perf_callchain_store(entry, next_ip);
for (;;) {
fp = (unsigned long __user *) sp;
if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp))
return;
if (level > 0 && read_user_stack_64(&fp[2], &next_ip))
return;
/*
* Note: the next_sp - sp >= signal frame size check
* is true when next_sp < sp, which can happen when
* transitioning from an alternate signal stack to the
* normal stack.
*/
if (next_sp - sp >= sizeof(struct signal_frame_64) &&
(is_sigreturn_64_address(next_ip, sp) ||
(level <= 1 && is_sigreturn_64_address(lr, sp))) &&
sane_signal_64_frame(sp)) {
/*
* This looks like an signal frame
*/
sigframe = (struct signal_frame_64 __user *) sp;
uregs = sigframe->uc.uc_mcontext.gp_regs;
if (read_user_stack_64(&uregs[PT_NIP], &next_ip) ||
read_user_stack_64(&uregs[PT_LNK], &lr) ||
read_user_stack_64(&uregs[PT_R1], &sp))
return;
level = 0;
perf_callchain_store(entry, PERF_CONTEXT_USER);
perf_callchain_store(entry, next_ip);
continue;
}
if (level == 0)
next_ip = lr;
perf_callchain_store(entry, next_ip);
++level;
sp = next_sp;
}
}
Commit Message: powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH
We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH
(currently 127), but we forgot to do the same for 64bit backtraces.
Cc: [email protected]
Signed-off-by: Anton Blanchard <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
CWE ID: CWE-399 | static void perf_callchain_user_64(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long sp, next_sp;
unsigned long next_ip;
unsigned long lr;
long level = 0;
struct signal_frame_64 __user *sigframe;
unsigned long __user *fp, *uregs;
next_ip = perf_instruction_pointer(regs);
lr = regs->link;
sp = regs->gpr[1];
perf_callchain_store(entry, next_ip);
while (entry->nr < PERF_MAX_STACK_DEPTH) {
fp = (unsigned long __user *) sp;
if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp))
return;
if (level > 0 && read_user_stack_64(&fp[2], &next_ip))
return;
/*
* Note: the next_sp - sp >= signal frame size check
* is true when next_sp < sp, which can happen when
* transitioning from an alternate signal stack to the
* normal stack.
*/
if (next_sp - sp >= sizeof(struct signal_frame_64) &&
(is_sigreturn_64_address(next_ip, sp) ||
(level <= 1 && is_sigreturn_64_address(lr, sp))) &&
sane_signal_64_frame(sp)) {
/*
* This looks like an signal frame
*/
sigframe = (struct signal_frame_64 __user *) sp;
uregs = sigframe->uc.uc_mcontext.gp_regs;
if (read_user_stack_64(&uregs[PT_NIP], &next_ip) ||
read_user_stack_64(&uregs[PT_LNK], &lr) ||
read_user_stack_64(&uregs[PT_R1], &sp))
return;
level = 0;
perf_callchain_store(entry, PERF_CONTEXT_USER);
perf_callchain_store(entry, next_ip);
continue;
}
if (level == 0)
next_ip = lr;
perf_callchain_store(entry, next_ip);
++level;
sp = next_sp;
}
}
| 166,587 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: u32 h264bsdInitDpb(
dpbStorage_t *dpb,
u32 picSizeInMbs,
u32 dpbSize,
u32 maxRefFrames,
u32 maxFrameNum,
u32 noReordering)
{
/* Variables */
u32 i;
/* Code */
ASSERT(picSizeInMbs);
ASSERT(maxRefFrames <= MAX_NUM_REF_PICS);
ASSERT(maxRefFrames <= dpbSize);
ASSERT(maxFrameNum);
ASSERT(dpbSize);
dpb->maxLongTermFrameIdx = NO_LONG_TERM_FRAME_INDICES;
dpb->maxRefFrames = MAX(maxRefFrames, 1);
if (noReordering)
dpb->dpbSize = dpb->maxRefFrames;
else
dpb->dpbSize = dpbSize;
dpb->maxFrameNum = maxFrameNum;
dpb->noReordering = noReordering;
dpb->fullness = 0;
dpb->numRefFrames = 0;
dpb->prevRefFrameNum = 0;
ALLOCATE(dpb->buffer, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t);
if (dpb->buffer == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->buffer, 0,
(MAX_NUM_REF_IDX_L0_ACTIVE + 1)*sizeof(dpbPicture_t));
for (i = 0; i < dpb->dpbSize + 1; i++)
{
/* Allocate needed amount of memory, which is:
* image size + 32 + 15, where 32 cames from the fact that in ARM OpenMax
* DL implementation Functions may read beyond the end of an array,
* by a maximum of 32 bytes. And +15 cames for the need to align memory
* to 16-byte boundary */
ALLOCATE(dpb->buffer[i].pAllocatedData, (picSizeInMbs*384 + 32+15), u8);
if (dpb->buffer[i].pAllocatedData == NULL)
return(MEMORY_ALLOCATION_ERROR);
dpb->buffer[i].data = ALIGN(dpb->buffer[i].pAllocatedData, 16);
}
ALLOCATE(dpb->list, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t*);
ALLOCATE(dpb->outBuf, dpb->dpbSize+1, dpbOutPicture_t);
if (dpb->list == NULL || dpb->outBuf == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->list, 0,
((MAX_NUM_REF_IDX_L0_ACTIVE + 1) * sizeof(dpbPicture_t*)) );
dpb->numOut = dpb->outIndex = 0;
return(HANTRO_OK);
}
Commit Message: Fix potential overflow
Bug: 28533562
Change-Id: I798ab24caa4c81f3ba564cad7c9ee019284fb702
CWE ID: CWE-119 | u32 h264bsdInitDpb(
dpbStorage_t *dpb,
u32 picSizeInMbs,
u32 dpbSize,
u32 maxRefFrames,
u32 maxFrameNum,
u32 noReordering)
{
/* Variables */
u32 i;
/* Code */
ASSERT(picSizeInMbs);
ASSERT(maxRefFrames <= MAX_NUM_REF_PICS);
ASSERT(maxRefFrames <= dpbSize);
ASSERT(maxFrameNum);
ASSERT(dpbSize);
// see comment in loop below about size calculation
if (picSizeInMbs > (UINT32_MAX - 32 - 15) / 384) {
ALOGE("b/28533562");
android_errorWriteLog(0x534e4554, "28533562");
return(MEMORY_ALLOCATION_ERROR);
}
dpb->maxLongTermFrameIdx = NO_LONG_TERM_FRAME_INDICES;
dpb->maxRefFrames = MAX(maxRefFrames, 1);
if (noReordering)
dpb->dpbSize = dpb->maxRefFrames;
else
dpb->dpbSize = dpbSize;
dpb->maxFrameNum = maxFrameNum;
dpb->noReordering = noReordering;
dpb->fullness = 0;
dpb->numRefFrames = 0;
dpb->prevRefFrameNum = 0;
ALLOCATE(dpb->buffer, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t);
if (dpb->buffer == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->buffer, 0,
(MAX_NUM_REF_IDX_L0_ACTIVE + 1)*sizeof(dpbPicture_t));
for (i = 0; i < dpb->dpbSize + 1; i++)
{
/* Allocate needed amount of memory, which is:
* image size + 32 + 15, where 32 cames from the fact that in ARM OpenMax
* DL implementation Functions may read beyond the end of an array,
* by a maximum of 32 bytes. And +15 cames for the need to align memory
* to 16-byte boundary */
ALLOCATE(dpb->buffer[i].pAllocatedData, (picSizeInMbs*384 + 32+15), u8);
if (dpb->buffer[i].pAllocatedData == NULL)
return(MEMORY_ALLOCATION_ERROR);
dpb->buffer[i].data = ALIGN(dpb->buffer[i].pAllocatedData, 16);
}
ALLOCATE(dpb->list, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t*);
ALLOCATE(dpb->outBuf, dpb->dpbSize+1, dpbOutPicture_t);
if (dpb->list == NULL || dpb->outBuf == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->list, 0,
((MAX_NUM_REF_IDX_L0_ACTIVE + 1) * sizeof(dpbPicture_t*)) );
dpb->numOut = dpb->outIndex = 0;
return(HANTRO_OK);
}
| 173,546 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
Commit Message: ALSA: compress: fix an integer overflow check
I previously added an integer overflow check here but looking at it now,
it's still buggy.
The bug happens in snd_compr_allocate_buffer(). We multiply
".fragments" and ".fragment_size" and that doesn't overflow but then we
save it in an unsigned int so it truncates the high bits away and we
allocate a smaller than expected size.
Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > INT_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
| 167,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadJBIGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickStatusType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
length,
y;
struct jbg_dec_state
jbig_info;
unsigned char
bit,
*buffer,
byte;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JBIG toolkit.
*/
jbg_dec_init(&jbig_info);
jbg_dec_maxsize(&jbig_info,(unsigned long) image->columns,(unsigned long)
image->rows);
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Read JBIG file.
*/
buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=JBG_EAGAIN;
do
{
length=(ssize_t) ReadBlob(image,MagickMaxBufferExtent,buffer);
if (length == 0)
break;
p=buffer;
while ((length > 0) && ((status == JBG_EAGAIN) || (status == JBG_EOK)))
{
size_t
count;
status=jbg_dec_in(&jbig_info,p,length,&count);
p+=count;
length-=(ssize_t) count;
}
} while ((status == JBG_EAGAIN) || (status == JBG_EOK));
/*
Create colormap.
*/
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->compression=JBIG2Compression;
if (AcquireImageColormap(image,2) == MagickFalse)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
image->colormap[0].red=0;
image->colormap[0].green=0;
image->colormap[0].blue=0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
image->x_resolution=300;
image->y_resolution=300;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert X bitmap image to pixel packets.
*/
p=jbg_dec_getimage(&jbig_info,0);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(*p++);
index=(byte & 0x80) ? 0 : 1;
bit++;
byte<<=1;
if (bit == 8)
bit=0;
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free scale resource.
*/
jbg_dec_free(&jbig_info);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadJBIGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickStatusType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
length,
y;
struct jbg_dec_state
jbig_info;
unsigned char
bit,
*buffer,
byte;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JBIG toolkit.
*/
jbg_dec_init(&jbig_info);
jbg_dec_maxsize(&jbig_info,(unsigned long) image->columns,(unsigned long)
image->rows);
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Read JBIG file.
*/
buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=JBG_EAGAIN;
do
{
length=(ssize_t) ReadBlob(image,MagickMaxBufferExtent,buffer);
if (length == 0)
break;
p=buffer;
while ((length > 0) && ((status == JBG_EAGAIN) || (status == JBG_EOK)))
{
size_t
count;
status=jbg_dec_in(&jbig_info,p,length,&count);
p+=count;
length-=(ssize_t) count;
}
} while ((status == JBG_EAGAIN) || (status == JBG_EOK));
/*
Create colormap.
*/
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->compression=JBIG2Compression;
if (AcquireImageColormap(image,2) == MagickFalse)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
image->colormap[0].red=0;
image->colormap[0].green=0;
image->colormap[0].blue=0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
image->x_resolution=300;
image->y_resolution=300;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert X bitmap image to pixel packets.
*/
p=jbg_dec_getimage(&jbig_info,0);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(*p++);
index=(byte & 0x80) ? 0 : 1;
bit++;
byte<<=1;
if (bit == 8)
bit=0;
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free scale resource.
*/
jbg_dec_free(&jbig_info);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GpuProcessHost::~GpuProcessHost() {
DCHECK(CalledOnValidThread());
SendOutstandingReplies();
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
if (software_rendering_) {
if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) {
gpu_enabled_ = false;
}
} else {
if (++g_gpu_crash_count >= kGpuMaxCrashCount) {
#if !defined(OS_CHROMEOS)
hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->BlacklistCard();
#endif
}
}
}
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
DIED_FIRST_TIME + g_gpu_crash_count,
GPU_PROCESS_LIFETIME_EVENT_MAX);
int exit_code;
base::TerminationStatus status = process_->GetTerminationStatus(&exit_code);
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
status,
base::TERMINATION_STATUS_MAX_ENUM);
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
exit_code,
content::RESULT_CODE_LAST_CODE);
}
#if defined(OS_WIN)
if (gpu_process_)
CloseHandle(gpu_process_);
#endif
while (!queued_messages_.empty()) {
delete queued_messages_.front();
queued_messages_.pop();
}
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&GpuProcessHostUIShim::Destroy, host_id_));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | GpuProcessHost::~GpuProcessHost() {
DCHECK(CalledOnValidThread());
SendOutstandingReplies();
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
if (software_rendering_) {
if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) {
gpu_enabled_ = false;
}
} else {
if (++g_gpu_crash_count >= kGpuMaxCrashCount) {
#if !defined(OS_CHROMEOS)
hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->BlacklistCard();
#endif
}
}
}
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
DIED_FIRST_TIME + g_gpu_crash_count,
GPU_PROCESS_LIFETIME_EVENT_MAX);
int exit_code;
base::TerminationStatus status = process_->GetTerminationStatus(&exit_code);
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
status,
base::TERMINATION_STATUS_MAX_ENUM);
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
exit_code,
content::RESULT_CODE_LAST_CODE);
}
while (!queued_messages_.empty()) {
delete queued_messages_.front();
queued_messages_.pop();
}
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&GpuProcessHostUIShim::Destroy, host_id_));
}
| 170,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int genl_register_family(struct genl_family *family)
{
int err, i;
int start = GENL_START_ALLOC, end = GENL_MAX_ID;
err = genl_validate_ops(family);
if (err)
return err;
genl_lock_all();
if (genl_family_find_byname(family->name)) {
err = -EEXIST;
goto errout_locked;
}
/*
* Sadly, a few cases need to be special-cased
* due to them having previously abused the API
* and having used their family ID also as their
* multicast group ID, so we use reserved IDs
* for both to be sure we can do that mapping.
*/
if (family == &genl_ctrl) {
/* and this needs to be special for initial family lookups */
start = end = GENL_ID_CTRL;
} else if (strcmp(family->name, "pmcraid") == 0) {
start = end = GENL_ID_PMCRAID;
} else if (strcmp(family->name, "VFS_DQUOT") == 0) {
start = end = GENL_ID_VFS_DQUOT;
}
if (family->maxattr && !family->parallel_ops) {
family->attrbuf = kmalloc_array(family->maxattr + 1,
sizeof(struct nlattr *),
GFP_KERNEL);
if (family->attrbuf == NULL) {
err = -ENOMEM;
goto errout_locked;
}
} else
family->attrbuf = NULL;
family->id = idr_alloc(&genl_fam_idr, family,
start, end + 1, GFP_KERNEL);
if (family->id < 0) {
err = family->id;
goto errout_locked;
}
err = genl_validate_assign_mc_groups(family);
if (err)
goto errout_remove;
genl_unlock_all();
/* send all events */
genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0);
for (i = 0; i < family->n_mcgrps; i++)
genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family,
&family->mcgrps[i], family->mcgrp_offset + i);
return 0;
errout_remove:
idr_remove(&genl_fam_idr, family->id);
kfree(family->attrbuf);
errout_locked:
genl_unlock_all();
return err;
}
Commit Message: genetlink: Fix a memory leak on error path
In genl_register_family(), when idr_alloc() fails,
we forget to free the memory we possibly allocate for
family->attrbuf.
Reported-by: Hulk Robot <[email protected]>
Fixes: 2ae0f17df1cd ("genetlink: use idr to track families")
Signed-off-by: YueHaibing <[email protected]>
Reviewed-by: Kirill Tkhai <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | int genl_register_family(struct genl_family *family)
{
int err, i;
int start = GENL_START_ALLOC, end = GENL_MAX_ID;
err = genl_validate_ops(family);
if (err)
return err;
genl_lock_all();
if (genl_family_find_byname(family->name)) {
err = -EEXIST;
goto errout_locked;
}
/*
* Sadly, a few cases need to be special-cased
* due to them having previously abused the API
* and having used their family ID also as their
* multicast group ID, so we use reserved IDs
* for both to be sure we can do that mapping.
*/
if (family == &genl_ctrl) {
/* and this needs to be special for initial family lookups */
start = end = GENL_ID_CTRL;
} else if (strcmp(family->name, "pmcraid") == 0) {
start = end = GENL_ID_PMCRAID;
} else if (strcmp(family->name, "VFS_DQUOT") == 0) {
start = end = GENL_ID_VFS_DQUOT;
}
if (family->maxattr && !family->parallel_ops) {
family->attrbuf = kmalloc_array(family->maxattr + 1,
sizeof(struct nlattr *),
GFP_KERNEL);
if (family->attrbuf == NULL) {
err = -ENOMEM;
goto errout_locked;
}
} else
family->attrbuf = NULL;
family->id = idr_alloc(&genl_fam_idr, family,
start, end + 1, GFP_KERNEL);
if (family->id < 0) {
err = family->id;
goto errout_free;
}
err = genl_validate_assign_mc_groups(family);
if (err)
goto errout_remove;
genl_unlock_all();
/* send all events */
genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0);
for (i = 0; i < family->n_mcgrps; i++)
genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family,
&family->mcgrps[i], family->mcgrp_offset + i);
return 0;
errout_remove:
idr_remove(&genl_fam_idr, family->id);
errout_free:
kfree(family->attrbuf);
errout_locked:
genl_unlock_all();
return err;
}
| 169,524 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
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 MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnMsgCreateWindow)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
| 171,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void XMLHttpRequest::networkError()
{
genericError();
if (!m_uploadComplete) {
m_uploadComplete = true;
if (m_upload && m_uploadEventsAllowed)
m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent));
}
m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent));
internalAbort();
}
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::networkError()
void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type)
{
if (!m_uploadComplete) {
m_uploadComplete = true;
if (m_upload && m_uploadEventsAllowed)
m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
}
m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
}
void XMLHttpRequest::handleNetworkError()
{
m_exceptionCode = NetworkError;
handleDidFailGeneric();
if (m_async) {
changeState(DONE);
dispatchEventAndLoadEnd(eventNames().errorEvent);
} else {
m_state = DONE;
}
internalAbort();
}
| 171,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::Track(
Segment* pSegment,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_element_start(element_start),
m_element_size(element_size),
content_encoding_entries_(NULL),
content_encoding_entries_end_(NULL)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Track::Track(
Track::Track(Segment* pSegment, long long element_start, long long element_size)
: m_pSegment(pSegment),
m_element_start(element_start),
m_element_size(element_size),
content_encoding_entries_(NULL),
content_encoding_entries_end_(NULL) {}
Track::~Track() {
Info& info = const_cast<Info&>(m_info);
info.Clear();
ContentEncoding** i = content_encoding_entries_;
ContentEncoding** const j = content_encoding_entries_end_;
while (i != j) {
ContentEncoding* const encoding = *i++;
delete encoding;
}
delete[] content_encoding_entries_;
}
| 174,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TabStyle::TabColors GM2TabStyle::CalculateColors() const {
const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider();
constexpr float kMinimumActiveContrastRatio = 6.05f;
constexpr float kMinimumInactiveContrastRatio = 4.61f;
constexpr float kMinimumHoveredContrastRatio = 5.02f;
constexpr float kMinimumPressedContrastRatio = 4.41f;
float expected_opacity = 0.0f;
if (tab_->IsActive()) {
expected_opacity = 1.0f;
} else if (tab_->IsSelected()) {
expected_opacity = kSelectedTabOpacity;
} else if (tab_->mouse_hovered()) {
expected_opacity = GetHoverOpacity();
}
const SkColor bg_color = color_utils::AlphaBlend(
tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE),
tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE),
expected_opacity);
SkColor title_color = tab_->controller()->GetTabForegroundColor(
expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color);
title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color);
const SkColor base_hovered_color = theme_provider->GetColor(
ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER);
const SkColor base_pressed_color = theme_provider->GetColor(
ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED);
const auto get_color_for_contrast_ratio = [](SkColor fg_color,
SkColor bg_color,
float contrast_ratio) {
const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast(
bg_color, fg_color, bg_color, contrast_ratio);
return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha);
};
const SkColor generated_icon_color = get_color_for_contrast_ratio(
title_color, bg_color,
tab_->IsActive() ? kMinimumActiveContrastRatio
: kMinimumInactiveContrastRatio);
const SkColor generated_hovered_color = get_color_for_contrast_ratio(
base_hovered_color, bg_color, kMinimumHoveredContrastRatio);
const SkColor generated_pressed_color = get_color_for_contrast_ratio(
base_pressed_color, bg_color, kMinimumPressedContrastRatio);
const SkColor generated_hovered_icon_color =
color_utils::GetColorWithMinimumContrast(title_color,
generated_hovered_color);
const SkColor generated_pressed_icon_color =
color_utils::GetColorWithMinimumContrast(title_color,
generated_pressed_color);
return {bg_color,
title_color,
generated_icon_color,
generated_hovered_icon_color,
generated_pressed_icon_color,
generated_hovered_color,
generated_pressed_color};
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | TabStyle::TabColors GM2TabStyle::CalculateColors() const {
const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider();
constexpr float kMinimumActiveContrastRatio = 6.05f;
constexpr float kMinimumInactiveContrastRatio = 4.61f;
constexpr float kMinimumHoveredContrastRatio = 5.02f;
constexpr float kMinimumPressedContrastRatio = 4.41f;
float expected_opacity = 0.0f;
if (tab_->IsActive()) {
expected_opacity = 1.0f;
} else if (tab_->IsSelected()) {
expected_opacity = kSelectedTabOpacity;
} else if (tab_->mouse_hovered()) {
expected_opacity = GetHoverOpacity();
}
const SkColor bg_color = color_utils::AlphaBlend(
GetTabBackgroundColor(TAB_ACTIVE), GetTabBackgroundColor(TAB_INACTIVE),
expected_opacity);
SkColor title_color = tab_->controller()->GetTabForegroundColor(
expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color);
title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color);
const SkColor base_hovered_color = theme_provider->GetColor(
ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER);
const SkColor base_pressed_color = theme_provider->GetColor(
ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED);
const auto get_color_for_contrast_ratio = [](SkColor fg_color,
SkColor bg_color,
float contrast_ratio) {
const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast(
bg_color, fg_color, bg_color, contrast_ratio);
return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha);
};
const SkColor generated_icon_color = get_color_for_contrast_ratio(
title_color, bg_color,
tab_->IsActive() ? kMinimumActiveContrastRatio
: kMinimumInactiveContrastRatio);
const SkColor generated_hovered_color = get_color_for_contrast_ratio(
base_hovered_color, bg_color, kMinimumHoveredContrastRatio);
const SkColor generated_pressed_color = get_color_for_contrast_ratio(
base_pressed_color, bg_color, kMinimumPressedContrastRatio);
const SkColor generated_hovered_icon_color =
color_utils::GetColorWithMinimumContrast(title_color,
generated_hovered_color);
const SkColor generated_pressed_icon_color =
color_utils::GetColorWithMinimumContrast(title_color,
generated_pressed_color);
return {bg_color,
title_color,
generated_icon_color,
generated_hovered_icon_color,
generated_pressed_icon_color,
generated_hovered_color,
generated_pressed_color};
}
| 172,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestFlashMessageLoop::~TestFlashMessageLoop() {
PP_DCHECK(!message_loop_);
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | TestFlashMessageLoop::~TestFlashMessageLoop() {
PP_DCHECK(!message_loop_);
ResetTestObject();
if (instance_so_)
instance_so_->clear_owner();
}
| 172,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data)
{
/* This suppresses [Last] button: assistant thinks that
* we never have this page ready unless we are on it
* -> therefore there is at least one non-ready page
* -> therefore it won't show [Last]
*/
/* If processing is finished and if it was terminated because of an error
* the event progress page is selected. So, it does not make sense to show
* the next step button and we MUST NOT clear warnings.
*/
if (!is_processing_finished())
{
/* some pages hide it, so restore it to it's default */
show_next_step_button();
clear_warnings();
}
gtk_widget_hide(g_btn_detail);
gtk_widget_hide(g_btn_onfail);
if (!g_expert_mode)
gtk_widget_hide(g_btn_repeat);
/* Save text fields if changed */
/* Must be called before any GUI operation because the following two
* functions causes recreating of the text items tabs, thus all updates to
* these tabs will be lost */
save_items_from_notepad();
save_text_from_text_view(g_tv_comment, FILENAME_COMMENT);
if (pages[PAGENO_SUMMARY].page_widget == page)
{
if (!g_expert_mode)
{
/* Skip intro screen */
int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL);
log_info("switching to page_no:%d", n);
gtk_notebook_set_current_page(assistant, n);
return;
}
}
if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page)
{
if (highlight_forbidden())
{
add_sensitive_data_warning();
show_warnings();
gtk_expander_set_expanded(g_exp_search, TRUE);
}
else
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE);
show_warnings();
}
if (pages[PAGENO_REVIEW_DATA].page_widget == page)
{
update_ls_details_checkboxes(g_event_selected);
gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt));
}
if (pages[PAGENO_EDIT_COMMENT].page_widget == page)
{
gtk_widget_show(g_btn_detail);
gtk_widget_set_sensitive(g_btn_next, false);
on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL);
}
if (pages[PAGENO_EVENT_PROGRESS].page_widget == page)
{
log_info("g_event_selected:'%s'", g_event_selected);
if (g_event_selected
&& g_event_selected[0]
) {
clear_warnings();
start_event_run(g_event_selected);
}
}
if(pages[PAGENO_EVENT_SELECTOR].page_widget == page)
{
if (!g_expert_mode && !g_auto_event_list)
hide_next_step_button();
}
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
CWE ID: CWE-200 | static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data)
{
/* This suppresses [Last] button: assistant thinks that
* we never have this page ready unless we are on it
* -> therefore there is at least one non-ready page
* -> therefore it won't show [Last]
*/
/* If processing is finished and if it was terminated because of an error
* the event progress page is selected. So, it does not make sense to show
* the next step button and we MUST NOT clear warnings.
*/
if (!is_processing_finished())
{
/* some pages hide it, so restore it to it's default */
show_next_step_button();
clear_warnings();
}
gtk_widget_hide(g_btn_detail);
gtk_widget_hide(g_btn_onfail);
if (!g_expert_mode)
gtk_widget_hide(g_btn_repeat);
/* Save text fields if changed */
/* Must be called before any GUI operation because the following two
* functions causes recreating of the text items tabs, thus all updates to
* these tabs will be lost */
save_items_from_notepad();
save_text_from_text_view(g_tv_comment, FILENAME_COMMENT);
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
if (pages[PAGENO_SUMMARY].page_widget == page)
{
if (!g_expert_mode)
{
/* Skip intro screen */
int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL);
log_info("switching to page_no:%d", n);
gtk_notebook_set_current_page(assistant, n);
return;
}
}
if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page)
{
if (highlight_forbidden())
{
add_sensitive_data_warning();
show_warnings();
gtk_expander_set_expanded(g_exp_search, TRUE);
}
else
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE);
show_warnings();
}
if (pages[PAGENO_REVIEW_DATA].page_widget == page)
{
update_ls_details_checkboxes(g_event_selected);
gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt));
}
if (pages[PAGENO_EDIT_COMMENT].page_widget == page)
{
gtk_widget_show(g_btn_detail);
gtk_widget_set_sensitive(g_btn_next, false);
on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL);
}
if (pages[PAGENO_EVENT_PROGRESS].page_widget == page)
{
log_info("g_event_selected:'%s'", g_event_selected);
if (g_event_selected
&& g_event_selected[0]
) {
clear_warnings();
start_event_run(g_event_selected);
}
}
if(pages[PAGENO_EVENT_SELECTOR].page_widget == page)
{
if (!g_expert_mode && !g_auto_event_list)
hide_next_step_button();
}
}
| 166,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125 | static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
| 169,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr insert, int isLRE)
{
xmlNodePtr copy;
if ((node->type == XML_DTD_NODE) || (insert == NULL))
return(NULL);
if ((node->type == XML_TEXT_NODE) ||
(node->type == XML_CDATA_SECTION_NODE))
return(xsltCopyText(ctxt, insert, node, 0));
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
if (node->type == XML_ELEMENT_NODE) {
/*
* Add namespaces as they are needed
*/
if (node->nsDef != NULL) {
/*
* TODO: Remove the LRE case in the refactored code
* gets enabled.
*/
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
/*
* URGENT TODO: The problem with this is that it does not
* copy over all namespace nodes in scope.
* The damn thing about this is, that we would need to
* use the xmlGetNsList(), for every single node; this is
* also done in xsltCopyTreeInternal(), but only for the top node.
*/
if (node->ns != NULL) {
if (isLRE) {
/*
* REVISIT TODO: Since the non-refactored code still does
* ns-aliasing, we need to call xsltGetNamespace() here.
* Remove this when ready.
*/
copy->ns = xsltGetNamespace(ctxt, node, node->ns, copy);
} else {
copy->ns = xsltGetSpecialNamespace(ctxt,
node, node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace.
*/
xsltGetSpecialNamespace(ctxt, node, NULL, NULL, copy);
}
}
} else {
xsltTransformError(ctxt, NULL, node,
"xsltShallowCopyElem: copy %s failed\n", node->name);
}
return(copy);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr insert, int isLRE)
{
xmlNodePtr copy;
if ((node->type == XML_DTD_NODE) || (insert == NULL))
return(NULL);
if ((node->type == XML_TEXT_NODE) ||
(node->type == XML_CDATA_SECTION_NODE))
return(xsltCopyText(ctxt, insert, node, 0));
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
if (copy == NULL) {
xsltTransformError(ctxt, NULL, node,
"xsltShallowCopyElem: copy failed\n");
return (copy);
}
if (node->type == XML_ELEMENT_NODE) {
/*
* Add namespaces as they are needed
*/
if (node->nsDef != NULL) {
/*
* TODO: Remove the LRE case in the refactored code
* gets enabled.
*/
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
/*
* URGENT TODO: The problem with this is that it does not
* copy over all namespace nodes in scope.
* The damn thing about this is, that we would need to
* use the xmlGetNsList(), for every single node; this is
* also done in xsltCopyTreeInternal(), but only for the top node.
*/
if (node->ns != NULL) {
if (isLRE) {
/*
* REVISIT TODO: Since the non-refactored code still does
* ns-aliasing, we need to call xsltGetNamespace() here.
* Remove this when ready.
*/
copy->ns = xsltGetNamespace(ctxt, node, node->ns, copy);
} else {
copy->ns = xsltGetSpecialNamespace(ctxt,
node, node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace.
*/
xsltGetSpecialNamespace(ctxt, node, NULL, NULL, copy);
}
}
} else {
xsltTransformError(ctxt, NULL, node,
"xsltShallowCopyElem: copy %s failed\n", node->name);
}
return(copy);
}
| 173,330 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UpdateContentLengthPrefsForDataReductionProxy(
int received_content_length, int original_content_length,
bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy,
base::Time now, PrefService* prefs) {
base::TimeDelta time_since_unix_epoch = now - base::Time::UnixEpoch();
const int kMinDaysSinceUnixEpoch = 365 * 2; // 2 years.
const int kMaxDaysSinceUnixEpoch = 365 * 1000; // 1000 years.
if (time_since_unix_epoch.InDays() < kMinDaysSinceUnixEpoch ||
time_since_unix_epoch.InDays() > kMaxDaysSinceUnixEpoch) {
return;
}
int64 then_internal = prefs->GetInt64(
prefs::kDailyHttpContentLengthLastUpdateDate);
base::Time then_midnight =
base::Time::FromInternalValue(then_internal).LocalMidnight();
base::Time midnight = now.LocalMidnight();
int days_since_last_update = (midnight - then_midnight).InDays();
DailyDataSavingUpdate total(
prefs::kDailyHttpOriginalContentLength,
prefs::kDailyHttpReceivedContentLength,
prefs);
total.UpdateForDataChange(days_since_last_update);
DailyDataSavingUpdate proxy_enabled(
prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled,
prefs::kDailyContentLengthWithDataReductionProxyEnabled,
prefs);
proxy_enabled.UpdateForDataChange(days_since_last_update);
DailyDataSavingUpdate via_proxy(
prefs::kDailyOriginalContentLengthViaDataReductionProxy,
prefs::kDailyContentLengthViaDataReductionProxy,
prefs);
via_proxy.UpdateForDataChange(days_since_last_update);
total.Add(original_content_length, received_content_length);
if (with_data_reduction_proxy_enabled) {
proxy_enabled.Add(original_content_length, received_content_length);
if (via_data_reduction_proxy) {
via_proxy.Add(original_content_length, received_content_length);
}
}
if (days_since_last_update) {
prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate,
midnight.ToInternalValue());
if (days_since_last_update == 1) {
RecordDailyContentLengthHistograms(
total.GetOriginalListPrefValue(kNumDaysInHistory - 2),
total.GetReceivedListPrefValue(kNumDaysInHistory - 2),
proxy_enabled.GetOriginalListPrefValue(kNumDaysInHistory - 2),
proxy_enabled.GetReceivedListPrefValue(kNumDaysInHistory - 2),
via_proxy.GetOriginalListPrefValue(kNumDaysInHistory - 2),
via_proxy.GetReceivedListPrefValue(kNumDaysInHistory - 2));
}
}
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void UpdateContentLengthPrefsForDataReductionProxy(
int received_content_length,
int original_content_length,
bool with_data_reduction_proxy_enabled,
DataReductionRequestType data_reduction_type,
base::Time now, PrefService* prefs) {
base::TimeDelta time_since_unix_epoch = now - base::Time::UnixEpoch();
const int kMinDaysSinceUnixEpoch = 365 * 2; // 2 years.
const int kMaxDaysSinceUnixEpoch = 365 * 1000; // 1000 years.
if (time_since_unix_epoch.InDays() < kMinDaysSinceUnixEpoch ||
time_since_unix_epoch.InDays() > kMaxDaysSinceUnixEpoch) {
return;
}
int64 then_internal = prefs->GetInt64(
prefs::kDailyHttpContentLengthLastUpdateDate);
base::Time then_midnight =
base::Time::FromInternalValue(then_internal).LocalMidnight();
base::Time midnight = now.LocalMidnight();
int days_since_last_update = (midnight - then_midnight).InDays();
DailyDataSavingUpdate total(
prefs::kDailyHttpOriginalContentLength,
prefs::kDailyHttpReceivedContentLength,
prefs);
total.UpdateForDataChange(days_since_last_update);
DailyDataSavingUpdate proxy_enabled(
prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled,
prefs::kDailyContentLengthWithDataReductionProxyEnabled,
prefs);
proxy_enabled.UpdateForDataChange(days_since_last_update);
DailyDataSavingUpdate via_proxy(
prefs::kDailyOriginalContentLengthViaDataReductionProxy,
prefs::kDailyContentLengthViaDataReductionProxy,
prefs);
via_proxy.UpdateForDataChange(days_since_last_update);
DailyContentLengthUpdate https(
prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled, prefs);
https.UpdateForDataChange(days_since_last_update);
DailyContentLengthUpdate short_bypass(
prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled,
prefs);
short_bypass.UpdateForDataChange(days_since_last_update);
DailyContentLengthUpdate long_bypass(
prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled, prefs);
long_bypass.UpdateForDataChange(days_since_last_update);
DailyContentLengthUpdate unknown(
prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled, prefs);
unknown.UpdateForDataChange(days_since_last_update);
total.Add(original_content_length, received_content_length);
if (with_data_reduction_proxy_enabled) {
proxy_enabled.Add(original_content_length, received_content_length);
// Ignore data source cases, if exist, when
// "with_data_reduction_proxy_enabled == false"
switch (data_reduction_type) {
case VIA_DATA_REDUCTION_PROXY:
via_proxy.Add(original_content_length, received_content_length);
break;
case OFF_THE_RECORD:
// We don't measure off-the-record data.
break;
case HTTPS:
https.Add(received_content_length);
break;
case SHORT_BYPASS:
short_bypass.Add(received_content_length);
break;
case LONG_BYPASS:
long_bypass.Add(received_content_length);
break;
case UNKNOWN_TYPE:
unknown.Add(received_content_length);
break;
}
}
if (days_since_last_update) {
prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate,
midnight.ToInternalValue());
if (days_since_last_update == 1) {
// Therefore (kNumDaysInHistory - 2) below.
RecordDailyContentLengthHistograms(
total.GetOriginalListPrefValue(kNumDaysInHistory - 2),
total.GetReceivedListPrefValue(kNumDaysInHistory - 2),
proxy_enabled.GetOriginalListPrefValue(kNumDaysInHistory - 2),
proxy_enabled.GetReceivedListPrefValue(kNumDaysInHistory - 2),
via_proxy.GetOriginalListPrefValue(kNumDaysInHistory - 2),
via_proxy.GetReceivedListPrefValue(kNumDaysInHistory - 2),
https.GetListPrefValue(kNumDaysInHistory - 2),
short_bypass.GetListPrefValue(kNumDaysInHistory - 2),
long_bypass.GetListPrefValue(kNumDaysInHistory - 2),
unknown.GetListPrefValue(kNumDaysInHistory - 2));
}
}
}
| 171,328 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeMockRenderThread::OnGetDefaultPrintSettings(
PrintMsg_Print_Params* params) {
if (printer_.get())
printer_->GetDefaultPrintSettings(params);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void ChromeMockRenderThread::OnGetDefaultPrintSettings(
PrintMsg_Print_Params* params) {
printer_->GetDefaultPrintSettings(params);
}
| 170,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::ContentCompression::~ContentCompression() {
delete [] settings;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | ContentEncoding::ContentCompression::~ContentCompression() {
delete[] settings;
}
| 174,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AutocompleteLog::AutocompleteLog(
const string16& text,
bool just_deleted_text,
AutocompleteInput::Type input_type,
size_t selected_index,
SessionID::id_type tab_id,
metrics::OmniboxEventProto::PageClassification current_page_classification,
base::TimeDelta elapsed_time_since_user_first_modified_omnibox,
size_t inline_autocompleted_length,
const AutocompleteResult& result)
: text(text),
just_deleted_text(just_deleted_text),
input_type(input_type),
selected_index(selected_index),
tab_id(tab_id),
current_page_classification(current_page_classification),
elapsed_time_since_user_first_modified_omnibox(
elapsed_time_since_user_first_modified_omnibox),
inline_autocompleted_length(inline_autocompleted_length),
result(result) {
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | AutocompleteLog::AutocompleteLog(
const string16& text,
bool just_deleted_text,
AutocompleteInput::Type input_type,
size_t selected_index,
SessionID::id_type tab_id,
metrics::OmniboxEventProto::PageClassification current_page_classification,
base::TimeDelta elapsed_time_since_user_first_modified_omnibox,
size_t inline_autocompleted_length,
const AutocompleteResult& result)
: text(text),
just_deleted_text(just_deleted_text),
input_type(input_type),
selected_index(selected_index),
tab_id(tab_id),
current_page_classification(current_page_classification),
elapsed_time_since_user_first_modified_omnibox(
elapsed_time_since_user_first_modified_omnibox),
inline_autocompleted_length(inline_autocompleted_length),
result(result),
providers_info() {
}
| 170,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() {
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL;
}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399 | PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() {
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL;
}
| 171,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetBurnLibrary(
BurnLibrary* library, bool own) {
library_->burn_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::SetBurnLibrary(
| 170,636 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_read_finish_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif /* PNG_READ_INTERLACING_SUPPORTED */
png_debug(1, "in png_read_finish_row");
png_ptr->row_number++;
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
png_memset_check(png_ptr, png_ptr->prev_row, 0,
png_ptr->rowbytes + 1);
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (!(png_ptr->num_rows))
continue;
}
else /* if (png_ptr->transformations & PNG_INTERLACE) */
break;
} while (png_ptr->iwidth == 0);
if (png_ptr->pass < 7)
return;
}
#endif /* PNG_READ_INTERLACING_SUPPORTED */
if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IDAT;
#endif
char extra;
int ret;
png_ptr->zstream.next_out = (Byte *)&extra;
png_ptr->zstream.avail_out = (uInt)1;
for (;;)
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_byte chunk_length[4];
png_crc_finish(png_ptr, 0);
png_read_data(png_ptr, chunk_length, 4);
png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression Error");
if (!(png_ptr->zstream.avail_out))
{
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
}
png_ptr->zstream.avail_out = 0;
}
if (png_ptr->idat_size || png_ptr->zstream.avail_in)
png_warning(png_ptr, "Extra compression data.");
inflateReset(&png_ptr->zstream);
png_ptr->mode |= PNG_AFTER_IDAT;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_read_finish_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif /* PNG_READ_INTERLACING_SUPPORTED */
png_debug(1, "in png_read_finish_row");
png_ptr->row_number++;
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
png_memset_check(png_ptr, png_ptr->prev_row, 0,
png_ptr->rowbytes + 1);
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (!(png_ptr->num_rows))
continue;
}
else /* if (png_ptr->transformations & PNG_INTERLACE) */
break;
} while (png_ptr->iwidth == 0);
if (png_ptr->pass < 7)
return;
}
#endif /* PNG_READ_INTERLACING_SUPPORTED */
if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IDAT;
#endif
char extra;
int ret;
png_ptr->zstream.next_out = (Byte *)&extra;
png_ptr->zstream.avail_out = (uInt)1;
for (;;)
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_byte chunk_length[4];
png_crc_finish(png_ptr, 0);
png_read_data(png_ptr, chunk_length, 4);
png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression Error");
if (!(png_ptr->zstream.avail_out))
{
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
}
png_ptr->zstream.avail_out = 0;
}
if (png_ptr->idat_size || png_ptr->zstream.avail_in)
png_warning(png_ptr, "Extra compression data.");
inflateReset(&png_ptr->zstream);
png_ptr->mode |= PNG_AFTER_IDAT;
}
| 172,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
Commit Message:
CWE ID: CWE-264 | NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
bool matched;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
| 164,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool attach()
{
GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(m_inspector);
if (m_inspectorWindow) {
gtk_container_remove(GTK_CONTAINER(m_inspectorWindow), GTK_WIDGET(inspectorView.get()));
gtk_widget_destroy(m_inspectorWindow);
m_inspectorWindow = 0;
}
GtkWidget* pane;
if (gtk_bin_get_child(GTK_BIN(m_parentWindow)) == GTK_WIDGET(m_webView)) {
GRefPtr<WebKitWebView> inspectedView = m_webView;
gtk_container_remove(GTK_CONTAINER(m_parentWindow), GTK_WIDGET(m_webView));
pane = gtk_paned_new(GTK_ORIENTATION_VERTICAL);
gtk_paned_add1(GTK_PANED(pane), GTK_WIDGET(m_webView));
gtk_container_add(GTK_CONTAINER(m_parentWindow), pane);
gtk_widget_show_all(pane);
} else
pane = gtk_bin_get_child(GTK_BIN(m_parentWindow));
gtk_paned_add2(GTK_PANED(pane), GTK_WIDGET(inspectorView.get()));
return InspectorTest::attach();
}
Commit Message: [GTK] Inspector should set a default attached height before being attached
https://bugs.webkit.org/show_bug.cgi?id=90767
Reviewed by Xan Lopez.
We are currently using the minimum attached height in
WebKitWebViewBase as the default height for the inspector when
attached. It would be easier for WebKitWebViewBase and embedders
implementing attach() if the inspector already had an attached
height set when it's being attached.
* UIProcess/API/gtk/WebKitWebViewBase.cpp:
(webkitWebViewBaseContainerAdd): Don't initialize
inspectorViewHeight.
(webkitWebViewBaseSetInspectorViewHeight): Allow to set the
inspector view height before having an inpector view, but only
queue a resize when the view already has an inspector view.
* UIProcess/API/gtk/tests/TestInspector.cpp:
(testInspectorDefault):
(testInspectorManualAttachDetach):
* UIProcess/gtk/WebInspectorProxyGtk.cpp:
(WebKit::WebInspectorProxy::platformAttach): Set the default
attached height before attach the inspector view.
git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | bool attach()
{
GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(m_inspector);
if (m_inspectorWindow) {
gtk_container_remove(GTK_CONTAINER(m_inspectorWindow), GTK_WIDGET(inspectorView.get()));
gtk_widget_destroy(m_inspectorWindow);
m_inspectorWindow = 0;
}
GtkWidget* pane;
if (gtk_bin_get_child(GTK_BIN(m_parentWindow)) == GTK_WIDGET(m_webView)) {
GRefPtr<WebKitWebView> inspectedView = m_webView;
gtk_container_remove(GTK_CONTAINER(m_parentWindow), GTK_WIDGET(m_webView));
pane = gtk_paned_new(GTK_ORIENTATION_VERTICAL);
gtk_paned_add1(GTK_PANED(pane), GTK_WIDGET(m_webView));
gtk_container_add(GTK_CONTAINER(m_parentWindow), pane);
gtk_widget_show_all(pane);
} else
pane = gtk_bin_get_child(GTK_BIN(m_parentWindow));
gtk_paned_set_position(GTK_PANED(pane), webkit_web_inspector_get_attached_height(m_inspector));
gtk_paned_add2(GTK_PANED(pane), GTK_WIDGET(inspectorView.get()));
return InspectorTest::attach();
}
| 171,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
Commit Message: udf: Check component length before reading it
Check that length specified in a component of a symlink fits in the
input buffer we are reading. Also properly ignore component length for
component types that do not use it. Otherwise we read memory after end
of buffer for corrupted udf image.
Reported-by: Carl Henrik Lunde <[email protected]>
CC: [email protected]
Signed-off-by: Jan Kara <[email protected]>
CWE ID: | static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
elen += sizeof(struct pathComponent);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0) {
elen += pc->lengthComponentIdent;
break;
}
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
elen += pc->lengthComponentIdent;
if (elen > fromlen)
return -EIO;
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
| 166,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
Commit Message:
CWE ID: CWE-20 | validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen < 0 || screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
| 165,270 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int exfat_mount(struct exfat* ef, const char* spec, const char* options)
{
int rc;
enum exfat_mode mode;
exfat_tzset();
memset(ef, 0, sizeof(struct exfat));
parse_options(ef, options);
if (match_option(options, "ro"))
mode = EXFAT_MODE_RO;
else if (match_option(options, "ro_fallback"))
mode = EXFAT_MODE_ANY;
else
mode = EXFAT_MODE_RW;
ef->dev = exfat_open(spec, mode);
if (ef->dev == NULL)
return -EIO;
if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO)
{
if (mode == EXFAT_MODE_ANY)
ef->ro = -1;
else
ef->ro = 1;
}
ef->sb = malloc(sizeof(struct exfat_super_block));
if (ef->sb == NULL)
{
exfat_close(ef->dev);
exfat_error("failed to allocate memory for the super block");
return -ENOMEM;
}
memset(ef->sb, 0, sizeof(struct exfat_super_block));
if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to read boot sector");
return -EIO;
}
if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("exFAT file system is not found");
return -EIO;
}
ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb));
if (ef->zero_cluster == NULL)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to allocate zero sector");
return -ENOMEM;
}
/* use zero_cluster as a temporary buffer for VBR checksum verification */
if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb)))
{
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb));
if (ef->sb->version.major != 1 || ef->sb->version.minor != 0)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
exfat_error("unsupported exFAT version: %hhu.%hhu",
ef->sb->version.major, ef->sb->version.minor);
free(ef->sb);
return -EIO;
}
if (ef->sb->fat_count != 1)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count);
free(ef->sb);
return -EIO;
}
/* officially exFAT supports cluster size up to 32 MB */
if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
exfat_error("too big cluster size: 2^%d",
(int) ef->sb->sector_bits + (int) ef->sb->spc_bits);
free(ef->sb);
return -EIO;
}
if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) >
exfat_get_size(ef->dev))
{
/* this can cause I/O errors later but we don't fail mounting to let
user rescue data */
exfat_warn("file system is larger than underlying device: "
"%"PRIu64" > %"PRIu64,
le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb),
exfat_get_size(ef->dev));
}
ef->root = malloc(sizeof(struct exfat_node));
if (ef->root == NULL)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to allocate root node");
return -ENOMEM;
}
memset(ef->root, 0, sizeof(struct exfat_node));
ef->root->flags = EXFAT_ATTRIB_DIR;
ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster);
ef->root->fptr_cluster = ef->root->start_cluster;
ef->root->name[0] = cpu_to_le16('\0');
ef->root->size = rootdir_size(ef);
if (ef->root->size == 0)
{
free(ef->root);
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
/* exFAT does not have time attributes for the root directory */
ef->root->mtime = 0;
ef->root->atime = 0;
/* always keep at least 1 reference to the root node */
exfat_get_node(ef->root);
rc = exfat_cache_directory(ef, ef->root);
if (rc != 0)
goto error;
if (ef->upcase == NULL)
{
exfat_error("upcase table is not found");
goto error;
}
if (ef->cmap.chunk == NULL)
{
exfat_error("clusters bitmap is not found");
goto error;
}
if (prepare_super_block(ef) != 0)
goto error;
return 0;
error:
exfat_put_node(ef, ef->root);
exfat_reset_cache(ef);
free(ef->root);
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
Commit Message: Check sector and cluster size before use.
Otherwise malformed FS can cause heap corruption.
CWE ID: CWE-119 | int exfat_mount(struct exfat* ef, const char* spec, const char* options)
{
int rc;
enum exfat_mode mode;
exfat_tzset();
memset(ef, 0, sizeof(struct exfat));
parse_options(ef, options);
if (match_option(options, "ro"))
mode = EXFAT_MODE_RO;
else if (match_option(options, "ro_fallback"))
mode = EXFAT_MODE_ANY;
else
mode = EXFAT_MODE_RW;
ef->dev = exfat_open(spec, mode);
if (ef->dev == NULL)
return -EIO;
if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO)
{
if (mode == EXFAT_MODE_ANY)
ef->ro = -1;
else
ef->ro = 1;
}
ef->sb = malloc(sizeof(struct exfat_super_block));
if (ef->sb == NULL)
{
exfat_close(ef->dev);
exfat_error("failed to allocate memory for the super block");
return -ENOMEM;
}
memset(ef->sb, 0, sizeof(struct exfat_super_block));
if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to read boot sector");
return -EIO;
}
if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("exFAT file system is not found");
return -EIO;
}
/* sector cannot be smaller than 512 bytes */
if (ef->sb->sector_bits < 9)
{
exfat_close(ef->dev);
exfat_error("too small sector size: 2^%hhd", ef->sb->sector_bits);
free(ef->sb);
return -EIO;
}
/* officially exFAT supports cluster size up to 32 MB */
if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25)
{
exfat_close(ef->dev);
exfat_error("too big cluster size: 2^(%hhd+%hhd)",
ef->sb->sector_bits, ef->sb->spc_bits);
free(ef->sb);
return -EIO;
}
ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb));
if (ef->zero_cluster == NULL)
{
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to allocate zero sector");
return -ENOMEM;
}
/* use zero_cluster as a temporary buffer for VBR checksum verification */
if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb)))
{
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb));
if (ef->sb->version.major != 1 || ef->sb->version.minor != 0)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
exfat_error("unsupported exFAT version: %hhu.%hhu",
ef->sb->version.major, ef->sb->version.minor);
free(ef->sb);
return -EIO;
}
if (ef->sb->fat_count != 1)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count);
free(ef->sb);
return -EIO;
}
if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) >
exfat_get_size(ef->dev))
{
/* this can cause I/O errors later but we don't fail mounting to let
user rescue data */
exfat_warn("file system is larger than underlying device: "
"%"PRIu64" > %"PRIu64,
le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb),
exfat_get_size(ef->dev));
}
ef->root = malloc(sizeof(struct exfat_node));
if (ef->root == NULL)
{
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
exfat_error("failed to allocate root node");
return -ENOMEM;
}
memset(ef->root, 0, sizeof(struct exfat_node));
ef->root->flags = EXFAT_ATTRIB_DIR;
ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster);
ef->root->fptr_cluster = ef->root->start_cluster;
ef->root->name[0] = cpu_to_le16('\0');
ef->root->size = rootdir_size(ef);
if (ef->root->size == 0)
{
free(ef->root);
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
/* exFAT does not have time attributes for the root directory */
ef->root->mtime = 0;
ef->root->atime = 0;
/* always keep at least 1 reference to the root node */
exfat_get_node(ef->root);
rc = exfat_cache_directory(ef, ef->root);
if (rc != 0)
goto error;
if (ef->upcase == NULL)
{
exfat_error("upcase table is not found");
goto error;
}
if (ef->cmap.chunk == NULL)
{
exfat_error("clusters bitmap is not found");
goto error;
}
if (prepare_super_block(ef) != 0)
goto error;
return 0;
error:
exfat_put_node(ef, ef->root);
exfat_reset_cache(ef);
free(ef->root);
free(ef->zero_cluster);
exfat_close(ef->dev);
free(ef->sb);
return -EIO;
}
| 168,867 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int reseed_required = 0;
if (drbg->state != DRBG_READY) {
rand_drbg_restart(drbg, NULL, 0, 0);
if (drbg->state == DRBG_ERROR) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == DRBG_UNINITIALISED) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
return 0;
}
}
if (outlen > drbg->max_request) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
return 0;
}
if (drbg->fork_count != rand_fork_count) {
drbg->fork_count = rand_fork_count;
reseed_required = 1;
}
}
Commit Message:
CWE ID: CWE-330 | int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int fork_id;
int reseed_required = 0;
if (drbg->state != DRBG_READY) {
rand_drbg_restart(drbg, NULL, 0, 0);
if (drbg->state == DRBG_ERROR) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == DRBG_UNINITIALISED) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
return 0;
}
}
if (outlen > drbg->max_request) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
return 0;
}
fork_id = openssl_get_fork_id();
if (drbg->fork_id != fork_id) {
drbg->fork_id = fork_id;
reseed_required = 1;
}
}
| 165,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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 <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource()
In loadRequest(), setResource() can call clear() synchronously:
DocumentThreadableLoader::clear()
DocumentThreadableLoader::handleError()
Resource::didAddClient()
RawResource::didAddClient()
and thus |m_client| can be null while resource() isn't null after setResource(),
causing crashes (Issue 595964).
This CL checks whether |*this| is destructed and
whether |m_client| is null after setResource().
BUG=595964
Review-Url: https://codereview.chromium.org/1902683002
Cr-Commit-Position: refs/heads/master@{#391001}
CWE ID: CWE-189 | void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
WeakPtr<DocumentThreadableLoader> self(m_weakFactory.createWeakPtr());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
// setResource() might call notifyFinished() synchronously, and thus
// clear() might be called and |this| may be dead here.
if (!self)
return;
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
// setResource() might call notifyFinished() and thus clear()
// synchronously, and in such cases ThreadableLoaderClient is
// already notified and |client| is null.
if (!client)
return;
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
| 171,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION,
SyncPromoUI::SOURCE_UNKNOWN);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
| 171,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
{
png_color palette[PNG_MAX_PALETTE_LENGTH];
int num, i;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
png_colorp pal_ptr;
#endif
png_debug(1, "in png_handle_PLTE");
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before PLTE");
else if (png_ptr->mode & PNG_HAVE_IDAT)
{
png_warning(png_ptr, "Invalid PLTE after IDAT");
png_crc_finish(png_ptr, length);
return;
}
else if (png_ptr->mode & PNG_HAVE_PLTE)
png_error(png_ptr, "Duplicate PLTE chunk");
png_ptr->mode |= PNG_HAVE_PLTE;
if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
{
png_warning(png_ptr,
"Ignoring PLTE chunk in grayscale PNG");
png_crc_finish(png_ptr, length);
return;
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_crc_finish(png_ptr, length);
return;
}
#endif
if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
{
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_warning(png_ptr, "Invalid palette chunk");
png_crc_finish(png_ptr, length);
return;
}
else
{
png_error(png_ptr, "Invalid palette chunk");
}
}
num = (int)length / 3;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
pal_ptr->red = buf[0];
pal_ptr->green = buf[1];
pal_ptr->blue = buf[2];
}
#else
for (i = 0; i < num; i++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
/* Don't depend upon png_color being any order */
palette[i].red = buf[0];
palette[i].green = buf[1];
palette[i].blue = buf[2];
}
#endif
/* If we actually NEED the PLTE chunk (ie for a paletted image), we do
* whatever the normal CRC configuration tells us. However, if we
* have an RGB image, the PLTE can be considered ancillary, so
* we will act as though it is.
*/
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
#endif
{
png_crc_finish(png_ptr, 0);
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
{
/* If we don't want to use the data from an ancillary chunk,
we have two options: an error abort, or a warning and we
ignore the data in this chunk (which should be OK, since
it's considered ancillary for a RGB or RGBA image). */
if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
{
if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
{
png_chunk_error(png_ptr, "CRC error");
}
else
{
png_chunk_warning(png_ptr, "CRC error");
return;
}
}
/* Otherwise, we (optionally) emit a warning and use the chunk. */
else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
{
png_chunk_warning(png_ptr, "CRC error");
}
}
#endif
png_set_PLTE(png_ptr, info_ptr, palette, num);
#ifdef PNG_READ_tRNS_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
{
if (png_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
png_ptr->num_trans = (png_uint_16)num;
}
if (info_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
info_ptr->num_trans = (png_uint_16)num;
}
}
}
#endif
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
{
png_color palette[PNG_MAX_PALETTE_LENGTH];
int max_palette_length, num, i;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
png_colorp pal_ptr;
#endif
png_debug(1, "in png_handle_PLTE");
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before PLTE");
else if (png_ptr->mode & PNG_HAVE_IDAT)
{
png_warning(png_ptr, "Invalid PLTE after IDAT");
png_crc_finish(png_ptr, length);
return;
}
else if (png_ptr->mode & PNG_HAVE_PLTE)
png_error(png_ptr, "Duplicate PLTE chunk");
png_ptr->mode |= PNG_HAVE_PLTE;
if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
{
png_warning(png_ptr,
"Ignoring PLTE chunk in grayscale PNG");
png_crc_finish(png_ptr, length);
return;
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_crc_finish(png_ptr, length);
return;
}
#endif
if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
{
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_warning(png_ptr, "Invalid palette chunk");
png_crc_finish(png_ptr, length);
return;
}
else
{
png_error(png_ptr, "Invalid palette chunk");
}
}
/* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
num = (int)length / 3;
/* If the palette has 256 or fewer entries but is too large for the bit
* depth, we don't issue an error, to preserve the behavior of previous
* libpng versions. We silently truncate the unused extra palette entries
* here.
*/
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
max_palette_length = (1 << png_ptr->bit_depth);
else
max_palette_length = PNG_MAX_PALETTE_LENGTH;
if (num > max_palette_length)
num = max_palette_length;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
pal_ptr->red = buf[0];
pal_ptr->green = buf[1];
pal_ptr->blue = buf[2];
}
#else
for (i = 0; i < num; i++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
/* Don't depend upon png_color being any order */
palette[i].red = buf[0];
palette[i].green = buf[1];
palette[i].blue = buf[2];
}
#endif
/* If we actually NEED the PLTE chunk (ie for a paletted image), we do
* whatever the normal CRC configuration tells us. However, if we
* have an RGB image, the PLTE can be considered ancillary, so
* we will act as though it is.
*/
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
#endif
{
png_crc_finish(png_ptr, (int) length - num * 3);
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
{
/* If we don't want to use the data from an ancillary chunk,
we have two options: an error abort, or a warning and we
ignore the data in this chunk (which should be OK, since
it's considered ancillary for a RGB or RGBA image). */
if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
{
if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
{
png_chunk_error(png_ptr, "CRC error");
}
else
{
png_chunk_warning(png_ptr, "CRC error");
return;
}
}
/* Otherwise, we (optionally) emit a warning and use the chunk. */
else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
{
png_chunk_warning(png_ptr, "CRC error");
}
}
#endif
png_set_PLTE(png_ptr, info_ptr, palette, num);
#ifdef PNG_READ_tRNS_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
{
if (png_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
png_ptr->num_trans = (png_uint_16)num;
}
if (info_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
info_ptr->num_trans = (png_uint_16)num;
}
}
}
#endif
}
| 172,177 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
{
kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);
wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));
kfree(ubufs);
}
Commit Message: vhost-net: fix use-after-free in vhost_net_flush
vhost_net_ubuf_put_and_wait has a confusing name:
it will actually also free it's argument.
Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01
"vhost-net: flush outstanding DMAs on memory change"
vhost_net_flush tries to use the argument after passing it
to vhost_net_ubuf_put_and_wait, this results
in use after free.
To fix, don't free the argument in vhost_net_ubuf_put_and_wait,
add an new API for callers that want to free ubufs.
Acked-by: Asias He <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
{
kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);
wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));
}
static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)
{
vhost_net_ubuf_put_and_wait(ubufs);
kfree(ubufs);
}
| 166,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pvscsi_convert_sglist(PVSCSIRequest *r)
{
int chunk_size;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length) {
while (!sg.resid) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
assert(data_length > 0);
chunk_size = MIN((unsigned) data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
Commit Message:
CWE ID: CWE-399 | pvscsi_convert_sglist(PVSCSIRequest *r)
{
uint32_t chunk_size, elmcnt = 0;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length && elmcnt < PVSCSI_MAX_SG_ELEM) {
while (!sg.resid && elmcnt++ < PVSCSI_MAX_SG_ELEM) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
chunk_size = MIN(data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
| 164,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DXVAVideoDecodeAccelerator::Decode(
const media::BitstreamBuffer& bitstream_buffer) {
DCHECK(CalledOnValidThread());
RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped),
"Invalid state: " << state_, ILLEGAL_STATE,);
base::win::ScopedComPtr<IMFSample> sample;
sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer,
renderer_process_,
input_stream_info_.cbSize,
input_stream_info_.cbAlignment));
RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample",
PLATFORM_FAILURE,);
if (!inputs_before_decode_) {
TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, "");
}
inputs_before_decode_++;
RETURN_AND_NOTIFY_ON_FAILURE(
SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0),
"Failed to create input sample", PLATFORM_FAILURE,);
HRESULT hr = decoder_->ProcessInput(0, sample, 0);
RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample",
PLATFORM_FAILURE,);
RETURN_AND_NOTIFY_ON_FAILURE(
SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0),
"Failed to send eos message to MFT", PLATFORM_FAILURE,);
state_ = kEosDrain;
last_input_buffer_id_ = bitstream_buffer.id();
DoDecode();
RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal),
"Failed to process output. Unexpected decoder state: " << state_,
ILLEGAL_STATE,);
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
&DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this,
bitstream_buffer.id()));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void DXVAVideoDecodeAccelerator::Decode(
const media::BitstreamBuffer& bitstream_buffer) {
DCHECK(CalledOnValidThread());
RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped),
"Invalid state: " << state_, ILLEGAL_STATE,);
base::win::ScopedComPtr<IMFSample> sample;
sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer,
input_stream_info_.cbSize,
input_stream_info_.cbAlignment));
RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample",
PLATFORM_FAILURE,);
if (!inputs_before_decode_) {
TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, "");
}
inputs_before_decode_++;
RETURN_AND_NOTIFY_ON_FAILURE(
SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0),
"Failed to create input sample", PLATFORM_FAILURE,);
HRESULT hr = decoder_->ProcessInput(0, sample, 0);
RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample",
PLATFORM_FAILURE,);
RETURN_AND_NOTIFY_ON_FAILURE(
SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0),
"Failed to send eos message to MFT", PLATFORM_FAILURE,);
state_ = kEosDrain;
last_input_buffer_id_ = bitstream_buffer.id();
DoDecode();
RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal),
"Failed to process output. Unexpected decoder state: " << state_,
ILLEGAL_STATE,);
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
&DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this,
bitstream_buffer.id()));
}
| 170,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAAC2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
mIsADTS = false;
} else if (aacParams->eAACStreamFormat
== OMX_AUDIO_AACStreamFormatMP4ADTS) {
mIsADTS = true;
} else {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidAacPresentation:
{
const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *aacPresParams =
(const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *)params;
if (aacPresParams->nMaxOutputChannels >= 0) {
int max;
if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; }
else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; }
else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; }
else {
max = aacPresParams->nMaxOutputChannels;
}
ALOGV("set nMaxOutputChannels=%d", max);
aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, max);
}
bool updateDrcWrapper = false;
if (aacPresParams->nDrcBoost >= 0) {
ALOGV("set nDrcBoost=%d", aacPresParams->nDrcBoost);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR,
aacPresParams->nDrcBoost);
updateDrcWrapper = true;
}
if (aacPresParams->nDrcCut >= 0) {
ALOGV("set nDrcCut=%d", aacPresParams->nDrcCut);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, aacPresParams->nDrcCut);
updateDrcWrapper = true;
}
if (aacPresParams->nHeavyCompression >= 0) {
ALOGV("set nHeavyCompression=%d", aacPresParams->nHeavyCompression);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY,
aacPresParams->nHeavyCompression);
updateDrcWrapper = true;
}
if (aacPresParams->nTargetReferenceLevel >= 0) {
ALOGV("set nTargetReferenceLevel=%d", aacPresParams->nTargetReferenceLevel);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET,
aacPresParams->nTargetReferenceLevel);
updateDrcWrapper = true;
}
if (aacPresParams->nEncodedTargetLevel >= 0) {
ALOGV("set nEncodedTargetLevel=%d", aacPresParams->nEncodedTargetLevel);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET,
aacPresParams->nEncodedTargetLevel);
updateDrcWrapper = true;
}
if (aacPresParams->nPCMLimiterEnable >= 0) {
aacDecoder_SetParam(mAACDecoder, AAC_PCM_LIMITER_ENABLE,
(aacPresParams->nPCMLimiterEnable != 0));
}
if (updateDrcWrapper) {
mDrcWrap.update();
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAAC2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
mIsADTS = false;
} else if (aacParams->eAACStreamFormat
== OMX_AUDIO_AACStreamFormatMP4ADTS) {
mIsADTS = true;
} else {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidAacPresentation:
{
const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *aacPresParams =
(const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *)params;
if (!isValidOMXParam(aacPresParams)) {
return OMX_ErrorBadParameter;
}
if (aacPresParams->nMaxOutputChannels >= 0) {
int max;
if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; }
else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; }
else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; }
else {
max = aacPresParams->nMaxOutputChannels;
}
ALOGV("set nMaxOutputChannels=%d", max);
aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, max);
}
bool updateDrcWrapper = false;
if (aacPresParams->nDrcBoost >= 0) {
ALOGV("set nDrcBoost=%d", aacPresParams->nDrcBoost);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR,
aacPresParams->nDrcBoost);
updateDrcWrapper = true;
}
if (aacPresParams->nDrcCut >= 0) {
ALOGV("set nDrcCut=%d", aacPresParams->nDrcCut);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, aacPresParams->nDrcCut);
updateDrcWrapper = true;
}
if (aacPresParams->nHeavyCompression >= 0) {
ALOGV("set nHeavyCompression=%d", aacPresParams->nHeavyCompression);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY,
aacPresParams->nHeavyCompression);
updateDrcWrapper = true;
}
if (aacPresParams->nTargetReferenceLevel >= 0) {
ALOGV("set nTargetReferenceLevel=%d", aacPresParams->nTargetReferenceLevel);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET,
aacPresParams->nTargetReferenceLevel);
updateDrcWrapper = true;
}
if (aacPresParams->nEncodedTargetLevel >= 0) {
ALOGV("set nEncodedTargetLevel=%d", aacPresParams->nEncodedTargetLevel);
mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET,
aacPresParams->nEncodedTargetLevel);
updateDrcWrapper = true;
}
if (aacPresParams->nPCMLimiterEnable >= 0) {
aacDecoder_SetParam(mAACDecoder, AAC_PCM_LIMITER_ENABLE,
(aacPresParams->nPCMLimiterEnable != 0));
}
if (updateDrcWrapper) {
mDrcWrap.update();
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb,
guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr)
{
guint32 tvb_len = tvb_reported_length (tvb);
guint32 off = offset;
guint32 len;
guint str_len;
guint32 ent;
guint32 idx;
guint8 peek;
DebugLog(("parse_wbxml_attr (level = %u, offset = %u)\n", level, offset));
/* Parse attributes */
while (off < tvb_len) {
peek = tvb_get_guint8 (tvb, off);
DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, "
"off = %u, tvb_len = %u\n", level, peek, off, tvb_len));
if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens
in state = ATTR */
case 0x00: /* SWITCH_PAGE */
*codepage_attr = tvb_get_guint8 (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 2,
" | Attr | A -->%3d "
"| SWITCH_PAGE (Attr code page) |",
*codepage_attr);
off += 2;
break;
case 0x01: /* END */
/* BEWARE
* The Attribute END token means either ">" or "/>"
* and as a consequence both must be treated separately.
* This is done in the TAG state parser.
*/
off++;
DebugLog(("ATTR: level = %u, Return: len = %u\n",
level, off - offset));
return (off - offset);
case 0x02: /* ENTITY */
ent = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| ENTITY "
"| %s'&#%u;'",
level, *codepage_attr, Indent (level), ent);
off += 1+len;
break;
case 0x03: /* STR_I */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| STR_I (Inline string) "
"| %s\'%s\'",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x04: /* LITERAL */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| LITERAL (Literal Attribute) "
"| %s<%s />",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
case 0x40: /* EXT_I_0 */
case 0x41: /* EXT_I_1 */
case 0x42: /* EXT_I_2 */
/* Extension tokens */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| EXT_I_%1x (Extension Token) "
"| %s(Inline string extension: \'%s\')",
level, *codepage_attr, peek & 0x0f, Indent (level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
/* 0x43 impossible in ATTR state */
/* 0x44 impossible in ATTR state */
case 0x80: /* EXT_T_0 */
case 0x81: /* EXT_T_1 */
case 0x82: /* EXT_T_2 */
/* Extension tokens */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| EXT_T_%1x (Extension Token) "
"| %s(Extension Token, integer value: %u)",
level, *codepage_attr, peek & 0x0f, Indent (level),
idx);
off += 1+len;
break;
case 0x83: /* STR_T */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| STR_T (Tableref string) "
"| %s\'%s\'",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
/* 0x84 impossible in ATTR state */
case 0xC0: /* EXT_0 */
case 0xC1: /* EXT_1 */
case 0xC2: /* EXT_2 */
/* Extension tokens */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| EXT_%1x (Extension Token) "
"| %s(Single-byte extension)",
level, *codepage_attr, peek & 0x0f, Indent (level));
off++;
break;
case 0xC3: /* OPAQUE - WBXML 1.1 and newer */
if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1 + len + idx,
" %3d | Attr | A %3d "
"| OPAQUE (Opaque data) "
"| %s(%d bytes of opaque data)",
level, *codepage_attr, Indent (level), idx);
off += 1+len+idx;
} else { /* WBXML 1.0 - RESERVED_2 token (invalid) */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| RESERVED_2 (Invalid Token!) "
"| WBXML 1.0 parsing stops here.",
level, *codepage_attr);
/* Stop processing as it is impossible to parse now */
off = tvb_len;
DebugLog(("ATTR: level = %u, Return: len = %u\n",
level, off - offset));
return (off - offset);
}
break;
/* 0xC4 impossible in ATTR state */
default:
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| %-10s (Invalid Token!) "
"| WBXML parsing stops here.",
level, *codepage_attr,
val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)"));
/* Move to end of buffer */
off = tvb_len;
break;
} else { /* Known atribute token */
if (peek & 0x80) { /* attrValue */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| Known attrValue 0x%02X "
"| %sattrValue_0x%02X",
level, *codepage_attr, peek & 0x7f, Indent (level),
peek);
off++;
} else { /* attrStart */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| Known attrStart 0x%02X "
"| %sattrStart_0x%02X",
level, *codepage_attr, peek & 0x7f, Indent (level),
peek);
off++;
}
}
} /* End WHILE */
DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n",
level, off - offset));
return (off - offset);
}
Commit Message: WBXML: add a basic sanity check for offset overflow
This is a naive approach allowing to detact that something went wrong,
without the need to replace all proto_tree_add_text() calls as what was
done in master-2.0 branch.
Bug: 12408
Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108
Reviewed-on: https://code.wireshark.org/review/15310
Reviewed-by: Michael Mann <[email protected]>
Reviewed-by: Pascal Quantin <[email protected]>
CWE ID: CWE-119 | parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb,
guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr)
{
guint32 tvb_len = tvb_reported_length (tvb);
guint32 off = offset, last_off;
guint32 len;
guint str_len;
guint32 ent;
guint32 idx;
guint8 peek;
DebugLog(("parse_wbxml_attr (level = %u, offset = %u)\n", level, offset));
/* Parse attributes */
last_off = off;
while (off < tvb_len) {
peek = tvb_get_guint8 (tvb, off);
DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, "
"off = %u, tvb_len = %u\n", level, peek, off, tvb_len));
if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens
in state = ATTR */
case 0x00: /* SWITCH_PAGE */
*codepage_attr = tvb_get_guint8 (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 2,
" | Attr | A -->%3d "
"| SWITCH_PAGE (Attr code page) |",
*codepage_attr);
off += 2;
break;
case 0x01: /* END */
/* BEWARE
* The Attribute END token means either ">" or "/>"
* and as a consequence both must be treated separately.
* This is done in the TAG state parser.
*/
off++;
DebugLog(("ATTR: level = %u, Return: len = %u\n",
level, off - offset));
return (off - offset);
case 0x02: /* ENTITY */
ent = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| ENTITY "
"| %s'&#%u;'",
level, *codepage_attr, Indent (level), ent);
off += 1+len;
break;
case 0x03: /* STR_I */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| STR_I (Inline string) "
"| %s\'%s\'",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x04: /* LITERAL */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| LITERAL (Literal Attribute) "
"| %s<%s />",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
case 0x40: /* EXT_I_0 */
case 0x41: /* EXT_I_1 */
case 0x42: /* EXT_I_2 */
/* Extension tokens */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| EXT_I_%1x (Extension Token) "
"| %s(Inline string extension: \'%s\')",
level, *codepage_attr, peek & 0x0f, Indent (level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
/* 0x43 impossible in ATTR state */
/* 0x44 impossible in ATTR state */
case 0x80: /* EXT_T_0 */
case 0x81: /* EXT_T_1 */
case 0x82: /* EXT_T_2 */
/* Extension tokens */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| EXT_T_%1x (Extension Token) "
"| %s(Extension Token, integer value: %u)",
level, *codepage_attr, peek & 0x0f, Indent (level),
idx);
off += 1+len;
break;
case 0x83: /* STR_T */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Attr | A %3d "
"| STR_T (Tableref string) "
"| %s\'%s\'",
level, *codepage_attr, Indent (level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
/* 0x84 impossible in ATTR state */
case 0xC0: /* EXT_0 */
case 0xC1: /* EXT_1 */
case 0xC2: /* EXT_2 */
/* Extension tokens */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| EXT_%1x (Extension Token) "
"| %s(Single-byte extension)",
level, *codepage_attr, peek & 0x0f, Indent (level));
off++;
break;
case 0xC3: /* OPAQUE - WBXML 1.1 and newer */
if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1 + len + idx,
" %3d | Attr | A %3d "
"| OPAQUE (Opaque data) "
"| %s(%d bytes of opaque data)",
level, *codepage_attr, Indent (level), idx);
off += 1+len+idx;
} else { /* WBXML 1.0 - RESERVED_2 token (invalid) */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| RESERVED_2 (Invalid Token!) "
"| WBXML 1.0 parsing stops here.",
level, *codepage_attr);
/* Stop processing as it is impossible to parse now */
off = tvb_len;
DebugLog(("ATTR: level = %u, Return: len = %u\n",
level, off - offset));
return (off - offset);
}
break;
/* 0xC4 impossible in ATTR state */
default:
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| %-10s (Invalid Token!) "
"| WBXML parsing stops here.",
level, *codepage_attr,
val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)"));
/* Move to end of buffer */
off = tvb_len;
break;
} else { /* Known atribute token */
if (peek & 0x80) { /* attrValue */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| Known attrValue 0x%02X "
"| %sattrValue_0x%02X",
level, *codepage_attr, peek & 0x7f, Indent (level),
peek);
off++;
} else { /* attrStart */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Attr | A %3d "
"| Known attrStart 0x%02X "
"| %sattrStart_0x%02X",
level, *codepage_attr, peek & 0x7f, Indent (level),
peek);
off++;
}
}
if (off < last_off) {
THROW(ReportedBoundsError);
}
last_off = off;
} /* End WHILE */
DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n",
level, off - offset));
return (off - offset);
}
| 167,139 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hwahc_security_create(struct hwahc *hwahc)
{
int result;
struct wusbhc *wusbhc = &hwahc->wusbhc;
struct usb_device *usb_dev = hwahc->wa.usb_dev;
struct device *dev = &usb_dev->dev;
struct usb_security_descriptor *secd;
struct usb_encryption_descriptor *etd;
void *itr, *top;
size_t itr_size, needed, bytes;
u8 index;
char buf[64];
/* Find the host's security descriptors in the config descr bundle */
index = (usb_dev->actconfig - usb_dev->config) /
sizeof(usb_dev->config[0]);
itr = usb_dev->rawdescriptors[index];
itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength);
top = itr + itr_size;
result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index],
le16_to_cpu(usb_dev->actconfig->desc.wTotalLength),
USB_DT_SECURITY, (void **) &secd);
if (result == -1) {
dev_warn(dev, "BUG? WUSB host has no security descriptors\n");
return 0;
}
needed = sizeof(*secd);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptor header (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
needed = le16_to_cpu(secd->wTotalLength);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptors (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
/* Walk over the sec descriptors and store CCM1's on wusbhc */
itr = (void *) secd + sizeof(*secd);
top = (void *) secd + le16_to_cpu(secd->wTotalLength);
index = 0;
bytes = 0;
while (itr < top) {
etd = itr;
if (top - itr < sizeof(*etd)) {
dev_err(dev, "BUG: bad host security descriptor; "
"not enough data (%zu vs %zu left)\n",
top - itr, sizeof(*etd));
break;
}
if (etd->bLength < sizeof(*etd)) {
dev_err(dev, "BUG: bad host encryption descriptor; "
"descriptor is too short "
"(%zu vs %zu needed)\n",
(size_t)etd->bLength, sizeof(*etd));
break;
}
itr += etd->bLength;
bytes += snprintf(buf + bytes, sizeof(buf) - bytes,
"%s (0x%02x) ",
wusb_et_name(etd->bEncryptionType),
etd->bEncryptionValue);
wusbhc->ccm1_etd = etd;
}
dev_info(dev, "supported encryption types: %s\n", buf);
if (wusbhc->ccm1_etd == NULL) {
dev_err(dev, "E: host doesn't support CCM-1 crypto\n");
return 0;
}
/* Pretty print what we support */
return 0;
}
Commit Message: USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400 | static int hwahc_security_create(struct hwahc *hwahc)
{
int result;
struct wusbhc *wusbhc = &hwahc->wusbhc;
struct usb_device *usb_dev = hwahc->wa.usb_dev;
struct device *dev = &usb_dev->dev;
struct usb_security_descriptor *secd;
struct usb_encryption_descriptor *etd;
void *itr, *top;
size_t itr_size, needed, bytes;
u8 index;
char buf[64];
/* Find the host's security descriptors in the config descr bundle */
index = (usb_dev->actconfig - usb_dev->config) /
sizeof(usb_dev->config[0]);
itr = usb_dev->rawdescriptors[index];
itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength);
top = itr + itr_size;
result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index],
le16_to_cpu(usb_dev->actconfig->desc.wTotalLength),
USB_DT_SECURITY, (void **) &secd, sizeof(*secd));
if (result == -1) {
dev_warn(dev, "BUG? WUSB host has no security descriptors\n");
return 0;
}
needed = sizeof(*secd);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptor header (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
needed = le16_to_cpu(secd->wTotalLength);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptors (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
/* Walk over the sec descriptors and store CCM1's on wusbhc */
itr = (void *) secd + sizeof(*secd);
top = (void *) secd + le16_to_cpu(secd->wTotalLength);
index = 0;
bytes = 0;
while (itr < top) {
etd = itr;
if (top - itr < sizeof(*etd)) {
dev_err(dev, "BUG: bad host security descriptor; "
"not enough data (%zu vs %zu left)\n",
top - itr, sizeof(*etd));
break;
}
if (etd->bLength < sizeof(*etd)) {
dev_err(dev, "BUG: bad host encryption descriptor; "
"descriptor is too short "
"(%zu vs %zu needed)\n",
(size_t)etd->bLength, sizeof(*etd));
break;
}
itr += etd->bLength;
bytes += snprintf(buf + bytes, sizeof(buf) - bytes,
"%s (0x%02x) ",
wusb_et_name(etd->bEncryptionType),
etd->bEncryptionValue);
wusbhc->ccm1_etd = etd;
}
dev_info(dev, "supported encryption types: %s\n", buf);
if (wusbhc->ccm1_etd == NULL) {
dev_err(dev, "E: host doesn't support CCM-1 crypto\n");
return 0;
}
/* Pretty print what we support */
return 0;
}
| 168,961 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
const EAS_I8 *pLoopEnd;
const EAS_I8 *pCurrentPhaseInt;
EAS_I32 numSamples;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 currentPhaseFrac;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I8 *pLoopStart;
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
/* calculate gain increment */
gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
gain = pWTIntFrame->prevGain << 16;
pCurrentPhaseInt = pWTVoice->pPhaseAccum;
currentPhaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->phaseIncrement;
pLoopStart = pWTVoice->pLoopStart;
pLoopEnd = pWTVoice->pLoopEnd + 1;
InterpolationLoop:
tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd);
if (tmp0 >= 0)
pCurrentPhaseInt = pLoopStart + tmp0;
tmp0 = *pCurrentPhaseInt;
tmp1 = *(pCurrentPhaseInt + 1);
tmp2 = phaseInc + currentPhaseFrac;
tmp1 = tmp1 - tmp0;
tmp1 = tmp1 * currentPhaseFrac;
tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS);
pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS);
currentPhaseFrac = tmp2 & PHASE_FRAC_MASK;
gain += gainIncrement;
tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
tmp0 = *pMixBuffer;
tmp2 = tmp1 * tmp2;
tmp2 = (tmp2 >> 9);
tmp0 = tmp2 + tmp0;
*pMixBuffer++ = tmp0;
numSamples--;
if (numSamples > 0)
goto InterpolationLoop;
pWTVoice->pPhaseAccum = pCurrentPhaseInt;
pWTVoice->phaseFrac = currentPhaseFrac;
/*lint -e{702} <avoid divide>*/
pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119 | void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
const EAS_I8 *pLoopEnd;
const EAS_I8 *pCurrentPhaseInt;
EAS_I32 numSamples;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 currentPhaseFrac;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I8 *pLoopStart;
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
/* calculate gain increment */
gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
gain = pWTIntFrame->prevGain << 16;
pCurrentPhaseInt = pWTVoice->pPhaseAccum;
currentPhaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->phaseIncrement;
pLoopStart = pWTVoice->pLoopStart;
pLoopEnd = pWTVoice->pLoopEnd + 1;
InterpolationLoop:
tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd);
if (tmp0 >= 0)
pCurrentPhaseInt = pLoopStart + tmp0;
tmp0 = *pCurrentPhaseInt;
tmp1 = *(pCurrentPhaseInt + 1);
tmp2 = phaseInc + currentPhaseFrac;
tmp1 = tmp1 - tmp0;
tmp1 = tmp1 * currentPhaseFrac;
tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS);
pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS);
currentPhaseFrac = tmp2 & PHASE_FRAC_MASK;
gain += gainIncrement;
tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
tmp0 = *pMixBuffer;
tmp2 = tmp1 * tmp2;
tmp2 = (tmp2 >> 9);
tmp0 = tmp2 + tmp0;
*pMixBuffer++ = tmp0;
numSamples--;
if (numSamples > 0)
goto InterpolationLoop;
pWTVoice->pPhaseAccum = pCurrentPhaseInt;
pWTVoice->phaseFrac = currentPhaseFrac;
/*lint -e{702} <avoid divide>*/
pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
}
| 174,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
int* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int encoded_pixels;
int rle_size;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx);
if (rle_size <= 0) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < rle_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 );
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int));
bitmap_caret += pixel_block_size;
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int));
bitmap_caret += (encoded_pixels * pixel_block_size);
buffer_caret += (encoded_pixels * pixel_block_size);
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
Commit Message: Fix OOB reads of the TGA decompression buffer
It is possible to craft TGA files which will overflow the decompression
buffer, but not the image's bitmap. Therefore we augment the check for the
bitmap's overflow with a check for the buffer's overflow.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6906
CWE ID: CWE-125 | int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
int* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int encoded_pixels;
int rle_size;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx);
if (rle_size <= 0) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < rle_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 );
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size
|| buffer_caret + pixel_block_size > rle_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int));
bitmap_caret += pixel_block_size;
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size
|| buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int));
bitmap_caret += (encoded_pixels * pixel_block_size);
buffer_caret += (encoded_pixels * pixel_block_size);
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
| 168,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int HttpStreamParser::DoReadHeadersComplete(int result) {
if (result == 0)
result = ERR_CONNECTION_CLOSED;
if (result < 0 && result != ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return result;
}
if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 &&
connection_->is_reused()) {
io_state_ = STATE_DONE;
return result;
}
if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED)
response_->response_time = base::Time::Now();
if (result == ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return ERR_EMPTY_RESPONSE;
} else {
int end_offset;
if (response_header_start_offset_ >= 0) {
io_state_ = STATE_READ_BODY_COMPLETE;
end_offset = read_buf_->offset();
} else {
io_state_ = STATE_BODY_PENDING;
end_offset = 0;
}
int rv = DoParseResponseHeaders(end_offset);
if (rv < 0)
return rv;
return result;
}
}
read_buf_->set_offset(read_buf_->offset() + result);
DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
DCHECK_GE(result, 0);
int end_of_header_offset = ParseResponseHeaders();
if (end_of_header_offset < -1)
return end_of_header_offset;
if (end_of_header_offset == -1) {
io_state_ = STATE_READ_HEADERS;
if (read_buf_->offset() - read_buf_unused_offset_ >= kMaxHeaderBufSize) {
io_state_ = STATE_DONE;
return ERR_RESPONSE_HEADERS_TOO_BIG;
}
} else {
read_buf_unused_offset_ = end_of_header_offset;
if (response_->headers->response_code() / 100 == 1) {
io_state_ = STATE_REQUEST_SENT;
response_header_start_offset_ = -1;
} else {
io_state_ = STATE_BODY_PENDING;
CalculateResponseBodySize();
if (response_body_length_ == 0) {
io_state_ = STATE_DONE;
int extra_bytes = read_buf_->offset() - read_buf_unused_offset_;
if (extra_bytes) {
CHECK_GT(extra_bytes, 0);
memmove(read_buf_->StartOfBuffer(),
read_buf_->StartOfBuffer() + read_buf_unused_offset_,
extra_bytes);
}
read_buf_->SetCapacity(extra_bytes);
read_buf_unused_offset_ = 0;
return OK;
}
}
}
return result;
}
Commit Message: net: don't process truncated headers on HTTPS connections.
This change causes us to not process any headers unless they are correctly
terminated with a \r\n\r\n sequence.
BUG=244260
Review URL: https://chromiumcodereview.appspot.com/15688012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | int HttpStreamParser::DoReadHeadersComplete(int result) {
if (result == 0)
result = ERR_CONNECTION_CLOSED;
if (result < 0 && result != ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return result;
}
if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 &&
connection_->is_reused()) {
io_state_ = STATE_DONE;
return result;
}
if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED)
response_->response_time = base::Time::Now();
if (result == ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return ERR_EMPTY_RESPONSE;
} else if (request_->url.SchemeIs("https")) {
// The connection was closed in the middle of the headers. For HTTPS we
// don't parse partial headers. Return a different error code so that we
// know that we shouldn't attempt to retry the request.
io_state_ = STATE_DONE;
return ERR_HEADERS_TRUNCATED;
}
// Parse things as well as we can and let the caller decide what to do.
int end_offset;
if (response_header_start_offset_ >= 0) {
io_state_ = STATE_READ_BODY_COMPLETE;
end_offset = read_buf_->offset();
} else {
io_state_ = STATE_BODY_PENDING;
end_offset = 0;
}
int rv = DoParseResponseHeaders(end_offset);
if (rv < 0)
return rv;
return result;
}
read_buf_->set_offset(read_buf_->offset() + result);
DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
DCHECK_GE(result, 0);
int end_of_header_offset = ParseResponseHeaders();
if (end_of_header_offset < -1)
return end_of_header_offset;
if (end_of_header_offset == -1) {
io_state_ = STATE_READ_HEADERS;
if (read_buf_->offset() - read_buf_unused_offset_ >= kMaxHeaderBufSize) {
io_state_ = STATE_DONE;
return ERR_RESPONSE_HEADERS_TOO_BIG;
}
} else {
read_buf_unused_offset_ = end_of_header_offset;
if (response_->headers->response_code() / 100 == 1) {
io_state_ = STATE_REQUEST_SENT;
response_header_start_offset_ = -1;
} else {
io_state_ = STATE_BODY_PENDING;
CalculateResponseBodySize();
if (response_body_length_ == 0) {
io_state_ = STATE_DONE;
int extra_bytes = read_buf_->offset() - read_buf_unused_offset_;
if (extra_bytes) {
CHECK_GT(extra_bytes, 0);
memmove(read_buf_->StartOfBuffer(),
read_buf_->StartOfBuffer() + read_buf_unused_offset_,
extra_bytes);
}
read_buf_->SetCapacity(extra_bytes);
read_buf_unused_offset_ = 0;
return OK;
}
}
}
return result;
}
| 171,258 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Chapters::Atom::GetTime(
const Chapters* pChapters,
long long timecode)
{
if (pChapters == NULL)
return -1;
Segment* const pSegment = pChapters->m_pSegment;
if (pSegment == NULL) // weird
return -1;
const SegmentInfo* const pInfo = pSegment->GetInfo();
if (pInfo == NULL)
return -1;
const long long timecode_scale = pInfo->GetTimeCodeScale();
if (timecode_scale < 1) // weird
return -1;
if (timecode < 0)
return -1;
const long long result = timecode_scale * timecode;
return result;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetTime(
| 174,361 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[])
{
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> method;
if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::TryCatch block(scriptState->isolate());
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(method), scriptState->getExecutionContext(), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) {
rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className);
block.ReThrow();
return v8::Local<v8::Value>();
}
return result;
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79 | v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[])
{
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> method;
if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::TryCatch block(scriptState->isolate());
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(method), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) {
rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className);
block.ReThrow();
return v8::Local<v8::Value>();
}
return result;
}
| 172,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static NTSTATUS do_connect(TALLOC_CTX *ctx,
const char *server,
const char *share,
const struct user_auth_info *auth_info,
bool show_sessetup,
bool force_encrypt,
int max_protocol,
int port,
int name_type,
struct cli_state **pcli)
{
struct cli_state *c = NULL;
char *servicename;
char *sharename;
char *newserver, *newshare;
const char *username;
const char *password;
const char *domain;
NTSTATUS status;
int flags = 0;
/* make a copy so we don't modify the global string 'service' */
servicename = talloc_strdup(ctx,share);
sharename += 2;
if (server == NULL) {
server = sharename;
}
sharename = strchr_m(sharename,'\\');
if (!sharename) {
return NT_STATUS_NO_MEMORY;
}
*sharename = 0;
sharename++;
}
Commit Message:
CWE ID: CWE-20 | static NTSTATUS do_connect(TALLOC_CTX *ctx,
const char *server,
const char *share,
const struct user_auth_info *auth_info,
bool show_sessetup,
bool force_encrypt,
int max_protocol,
int port,
int name_type,
struct cli_state **pcli)
{
struct cli_state *c = NULL;
char *servicename;
char *sharename;
char *newserver, *newshare;
const char *username;
const char *password;
const char *domain;
NTSTATUS status;
int flags = 0;
int signing_state = get_cmdline_auth_info_signing_state(auth_info);
if (force_encrypt) {
signing_state = SMB_SIGNING_REQUIRED;
}
/* make a copy so we don't modify the global string 'service' */
servicename = talloc_strdup(ctx,share);
sharename += 2;
if (server == NULL) {
server = sharename;
}
sharename = strchr_m(sharename,'\\');
if (!sharename) {
return NT_STATUS_NO_MEMORY;
}
*sharename = 0;
sharename++;
}
| 164,676 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
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 | xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
| 171,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that,
png_const_structp pp, PNG_CONST transform_display *display)
{
PNG_CONST unsigned int scale = (1U<<that->sample_depth)-1;
UNUSED(this)
UNUSED(pp)
UNUSED(display)
/* At the end recalculate the digitized red green and blue values according
* to the current sample_depth of the pixel.
*
* The sample value is simply scaled to the maximum, checking for over
* and underflow (which can both happen for some image transforms,
* including simple size scaling, though libpng doesn't do that at present.
*/
that->red = sample_scale(that->redf, scale);
/* The error value is increased, at the end, according to the lowest sBIT
* value seen. Common sense tells us that the intermediate integer
* representations are no more accurate than +/- 0.5 in the integral values,
* the sBIT allows the implementation to be worse than this. In addition the
* PNG specification actually permits any error within the range (-1..+1),
* but that is ignored here. Instead the final digitized value is compared,
* below to the digitized value of the error limits - this has the net effect
* of allowing (almost) +/-1 in the output value. It's difficult to see how
* any algorithm that digitizes intermediate results can be more accurate.
*/
that->rede += 1./(2*((1U<<that->red_sBIT)-1));
if (that->colour_type & PNG_COLOR_MASK_COLOR)
{
that->green = sample_scale(that->greenf, scale);
that->blue = sample_scale(that->bluef, scale);
that->greene += 1./(2*((1U<<that->green_sBIT)-1));
that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
}
else
{
that->blue = that->green = that->red;
that->bluef = that->greenf = that->redf;
that->bluee = that->greene = that->rede;
}
if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
that->colour_type == PNG_COLOR_TYPE_PALETTE)
{
that->alpha = sample_scale(that->alphaf, scale);
that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
}
else
{
that->alpha = scale; /* opaque */
that->alpha = 1; /* Override this. */
that->alphae = 0; /* It's exact ;-) */
}
}
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_mod_end(PNG_CONST image_transform *this, image_pixel *that,
image_transform_mod_end(const image_transform *this, image_pixel *that,
png_const_structp pp, const transform_display *display)
{
const unsigned int scale = (1U<<that->sample_depth)-1;
const int sig_bits = that->sig_bits;
UNUSED(this)
UNUSED(pp)
UNUSED(display)
/* At the end recalculate the digitized red green and blue values according
* to the current sample_depth of the pixel.
*
* The sample value is simply scaled to the maximum, checking for over
* and underflow (which can both happen for some image transforms,
* including simple size scaling, though libpng doesn't do that at present.
*/
that->red = sample_scale(that->redf, scale);
/* This is a bit bogus; really the above calculation should use the red_sBIT
* value, not sample_depth, but because libpng does png_set_shift by just
* shifting the bits we get errors if we don't do it the same way.
*/
if (sig_bits && that->red_sBIT < that->sample_depth)
that->red >>= that->sample_depth - that->red_sBIT;
/* The error value is increased, at the end, according to the lowest sBIT
* value seen. Common sense tells us that the intermediate integer
* representations are no more accurate than +/- 0.5 in the integral values,
* the sBIT allows the implementation to be worse than this. In addition the
* PNG specification actually permits any error within the range (-1..+1),
* but that is ignored here. Instead the final digitized value is compared,
* below to the digitized value of the error limits - this has the net effect
* of allowing (almost) +/-1 in the output value. It's difficult to see how
* any algorithm that digitizes intermediate results can be more accurate.
*/
that->rede += 1./(2*((1U<<that->red_sBIT)-1));
if (that->colour_type & PNG_COLOR_MASK_COLOR)
{
that->green = sample_scale(that->greenf, scale);
if (sig_bits && that->green_sBIT < that->sample_depth)
that->green >>= that->sample_depth - that->green_sBIT;
that->blue = sample_scale(that->bluef, scale);
if (sig_bits && that->blue_sBIT < that->sample_depth)
that->blue >>= that->sample_depth - that->blue_sBIT;
that->greene += 1./(2*((1U<<that->green_sBIT)-1));
that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
}
else
{
that->blue = that->green = that->red;
that->bluef = that->greenf = that->redf;
that->bluee = that->greene = that->rede;
}
if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
that->colour_type == PNG_COLOR_TYPE_PALETTE)
{
that->alpha = sample_scale(that->alphaf, scale);
that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
}
else
{
that->alpha = scale; /* opaque */
that->alphaf = 1; /* Override this. */
that->alphae = 0; /* It's exact ;-) */
}
if (sig_bits && that->alpha_sBIT < that->sample_depth)
that->alpha >>= that->sample_depth - that->alpha_sBIT;
}
| 173,623 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
tty_lock();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
tty_unlock();
mutex_unlock(&tty_mutex);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
tty_unlock();
return PTR_ERR(tty);
}
retval = tty_add_file(tty, filp);
if (retval) {
tty_unlock();
tty_release(inode, filp);
return retval;
}
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_unlock(); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
tty_lock();
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
tty_unlock();
goto retry_open;
}
tty_unlock();
mutex_lock(&tty_mutex);
tty_lock();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
tty_unlock();
mutex_unlock(&tty_mutex);
return 0;
}
Commit Message: TTY: drop driver reference in tty_open fail path
When tty_driver_lookup_tty fails in tty_open, we forget to drop a
reference to the tty driver. This was added by commit 4a2b5fddd5 (Move
tty lookup/reopen to caller).
Fix that by adding tty_driver_kref_put to the fail path.
I will refactor the code later. This is for the ease of backporting to
stable.
Introduced-in: v2.6.28-rc2
Signed-off-by: Jiri Slaby <[email protected]>
Cc: stable <[email protected]>
Cc: Alan Cox <[email protected]>
Acked-by: Sukadev Bhattiprolu <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
tty_lock();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
tty_unlock();
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
tty_unlock();
return PTR_ERR(tty);
}
retval = tty_add_file(tty, filp);
if (retval) {
tty_unlock();
tty_release(inode, filp);
return retval;
}
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_unlock(); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
tty_lock();
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
tty_unlock();
goto retry_open;
}
tty_unlock();
mutex_lock(&tty_mutex);
tty_lock();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
tty_unlock();
mutex_unlock(&tty_mutex);
return 0;
}
| 167,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void perf_event_disable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Disable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_disable, event);
return;
}
retry:
if (!task_function_call(task, __perf_event_disable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the event is still active, we need to retry the cross-call.
*/
if (event->state == PERF_EVENT_STATE_ACTIVE) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since we have the lock this context can't be scheduled
* in, so we can change the state safely.
*/
if (event->state == PERF_EVENT_STATE_INACTIVE) {
update_group_times(event);
event->state = PERF_EVENT_STATE_OFF;
}
raw_spin_unlock_irq(&ctx->lock);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | void perf_event_disable(struct perf_event *event)
static void _perf_event_disable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Disable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_disable, event);
return;
}
retry:
if (!task_function_call(task, __perf_event_disable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the event is still active, we need to retry the cross-call.
*/
if (event->state == PERF_EVENT_STATE_ACTIVE) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since we have the lock this context can't be scheduled
* in, so we can change the state safely.
*/
if (event->state == PERF_EVENT_STATE_INACTIVE) {
update_group_times(event);
event->state = PERF_EVENT_STATE_OFF;
}
raw_spin_unlock_irq(&ctx->lock);
}
| 166,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GLSurfaceEGLSurfaceControl::SwapBuffersAsync(
SwapCompletionCallback completion_callback,
PresentationCallback presentation_callback) {
CommitPendingTransaction(std::move(completion_callback),
std::move(presentation_callback));
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | void GLSurfaceEGLSurfaceControl::SwapBuffersAsync(
gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes(
PresentationCallback callback) {
NOTREACHED();
return gfx::SwapResult::SWAP_FAILED;
}
| 172,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269 | static int store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 168,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
struct iovec *iovec)
{
if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = kiocb->ki_nbytes;
*nr_segs = 1;
return 0;
}
Commit Message: AIO: properly check iovec sizes
In Linus's tree, the iovec code has been reworked massively, but in
older kernels the AIO layer should be checking this before passing the
request on to other layers.
Many thanks to Ben Hawkes of Google Project Zero for pointing out the
issue.
Reported-by: Ben Hawkes <[email protected]>
Acked-by: Benjamin LaHaise <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
struct iovec *iovec)
{
size_t len = kiocb->ki_nbytes;
if (len > MAX_RW_COUNT)
len = MAX_RW_COUNT;
if (unlikely(!access_ok(!rw, buf, len)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = len;
*nr_segs = 1;
return 0;
}
| 167,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
if (is_frameless_)
return min_size;
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
| 170,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WorkerProcessLauncher::Core::StopWorker() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (launch_success_timer_->IsRunning()) {
launch_success_timer_->Stop();
launch_backoff_.InformOfRequest(false);
}
self_ = this;
ipc_enabled_ = false;
if (process_watcher_.GetWatchedObject() != NULL) {
launcher_delegate_->KillProcess(CONTROL_C_EXIT);
return;
}
DCHECK(process_watcher_.GetWatchedObject() == NULL);
ipc_error_timer_->Stop();
process_exit_event_.Close();
if (stopping_) {
ipc_error_timer_.reset();
launch_timer_.reset();
self_ = NULL;
return;
}
self_ = NULL;
DWORD exit_code = launcher_delegate_->GetExitCode();
if (kMinPermanentErrorExitCode <= exit_code &&
exit_code <= kMaxPermanentErrorExitCode) {
worker_delegate_->OnPermanentError();
return;
}
launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(),
this, &Core::LaunchWorker);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void WorkerProcessLauncher::Core::StopWorker() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
// Keep the object alive in case one of delegates decides to delete |this|.
scoped_refptr<Core> self = this;
if (launch_success_timer_->IsRunning()) {
launch_success_timer_->Stop();
launch_backoff_.InformOfRequest(false);
}
ipc_enabled_ = false;
if (process_watcher_.GetWatchedObject() != NULL) {
launcher_delegate_->KillProcess(CONTROL_C_EXIT);
// Wait until the process is actually stopped if the caller keeps
// a reference to |this|. Otherwise terminate everything right now - there
// won't be a second chance.
if (!stopping_)
return;
process_watcher_.StopWatching();
}
ipc_error_timer_->Stop();
process_exit_event_.Close();
if (stopping_) {
ipc_error_timer_.reset();
launch_timer_.reset();
return;
}
if (launcher_delegate_->IsPermanentError(launch_backoff_.failure_count())) {
if (!stopping_)
worker_delegate_->OnPermanentError();
} else {
// Schedule the next attempt to launch the worker process.
launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(),
this, &Core::LaunchWorker);
}
}
| 171,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
}
| 168,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ps_files_valid_key(const char *key)
{
size_t len;
const char *p;
char c;
int ret = 1;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = 0;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > 128) {
ret = 0;
}
return ret;
}
Commit Message:
CWE ID: CWE-264 | static int ps_files_valid_key(const char *key)
| 164,871 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
sctp_socket_type_t type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
struct sctp_bind_hashbucket *head;
struct list_head tmplist;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
if (oldsp->do_auto_asconf) {
memcpy(&tmplist, &newsp->auto_asconf_list, sizeof(tmplist));
inet_sk_copy_descendant(newsk, oldsk);
memcpy(&newsp->auto_asconf_list, &tmplist, sizeof(tmplist));
} else
inet_sk_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
inet_sk(oldsk)->inet_num)];
local_bh_disable();
spin_lock(&head->lock);
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
spin_unlock(&head->lock);
local_bh_enable();
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr, GFP_KERNEL);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
skb_queue_head_init(&newsp->pd_lobby);
atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk, NULL);
}
sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*
* The caller has just allocated newsk so we can guarantee that other
* paths won't try to lock it and then oldsk.
*/
lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
sctp_assoc_migrate(assoc, newsk);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
newsk->sk_shutdown |= RCV_SHUTDOWN;
newsk->sk_state = SCTP_SS_ESTABLISHED;
release_sock(newsk);
}
Commit Message: sctp: fix ASCONF list handling
->auto_asconf_splist is per namespace and mangled by functions like
sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization.
Also, the call to inet_sk_copy_descendant() was backuping
->auto_asconf_list through the copy but was not honoring
->do_auto_asconf, which could lead to list corruption if it was
different between both sockets.
This commit thus fixes the list handling by using ->addr_wq_lock
spinlock to protect the list. A special handling is done upon socket
creation and destruction for that. Error handlig on sctp_init_sock()
will never return an error after having initialized asconf, so
sctp_destroy_sock() can be called without addrq_wq_lock. The lock now
will be take on sctp_close_sock(), before locking the socket, so we
don't do it in inverse order compared to sctp_addr_wq_timeout_handler().
Instead of taking the lock on sctp_sock_migrate() for copying and
restoring the list values, it's preferred to avoid rewritting it by
implementing sctp_copy_descendant().
Issue was found with a test application that kept flipping sysctl
default_auto_asconf on and off, but one could trigger it by issuing
simultaneous setsockopt() calls on multiple sockets or by
creating/destroying sockets fast enough. This is only triggerable
locally.
Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).")
Reported-by: Ji Jianwen <[email protected]>
Suggested-by: Neil Horman <[email protected]>
Suggested-by: Hannes Frederic Sowa <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
sctp_socket_type_t type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
struct sctp_bind_hashbucket *head;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
sctp_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
inet_sk(oldsk)->inet_num)];
local_bh_disable();
spin_lock(&head->lock);
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
spin_unlock(&head->lock);
local_bh_enable();
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr, GFP_KERNEL);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
skb_queue_head_init(&newsp->pd_lobby);
atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk, NULL);
}
sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*
* The caller has just allocated newsk so we can guarantee that other
* paths won't try to lock it and then oldsk.
*/
lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
sctp_assoc_migrate(assoc, newsk);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
newsk->sk_shutdown |= RCV_SHUTDOWN;
newsk->sk_state = SCTP_SS_ESTABLISHED;
release_sock(newsk);
}
| 166,631 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLES2DecoderImpl::SimulateAttrib0(GLuint max_vertex_accessed) {
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return false;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_.GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return false;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
GLsizei num_vertices = max_vertex_accessed + 1;
GLsizei size_needed = num_vertices * sizeof(Vec4); // NOLINT
if (size_needed > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
return true;
}
Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0."""
TEST=none
BUG=95625
[email protected]
Review URL: http://codereview.chromium.org/7796016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool GLES2DecoderImpl::SimulateAttrib0(GLuint max_vertex_accessed) {
bool GLES2DecoderImpl::SimulateAttrib0(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_.GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
// Make a buffer with a single repeated vec4 value enough to
// simulate the constant value that is supposed to be here.
// This is required to emulate GLES2 on GL.
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
if (static_cast<GLsizei>(size_needed) > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
*simulated = true;
return true;
}
| 170,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SkiaOutputSurfaceImpl::Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
bool use_stencil) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (initialize_waitable_event_) {
initialize_waitable_event_->Wait();
initialize_waitable_event_ = nullptr;
}
SkSurfaceCharacterization* characterization = nullptr;
if (characterization_.isValid()) {
characterization_ =
characterization_.createResized(size.width(), size.height());
RecreateRootRecorder();
} else {
characterization = &characterization_;
initialize_waitable_event_ = std::make_unique<base::WaitableEvent>(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
}
auto callback = base::BindOnce(
&SkiaOutputSurfaceImplOnGpu::Reshape,
base::Unretained(impl_on_gpu_.get()), size, device_scale_factor,
std::move(color_space), has_alpha, use_stencil, pre_transform_,
characterization, initialize_waitable_event_.get());
ScheduleGpuTask(std::move(callback), std::vector<gpu::SyncToken>());
}
Commit Message: SkiaRenderer: Support changing color space
SkiaOutputSurfaceImpl did not handle the color space changing after it
was created previously. The SkSurfaceCharacterization color space was
only set during the first time Reshape() ran when the charactization is
returned from the GPU thread. If the color space was changed later the
SkSurface and SkDDL color spaces no longer matched and draw failed.
Bug: 1009452
Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811
Reviewed-by: Peng Huang <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#702946}
CWE ID: CWE-704 | void SkiaOutputSurfaceImpl::Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
bool use_stencil) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (initialize_waitable_event_) {
initialize_waitable_event_->Wait();
initialize_waitable_event_.reset();
}
SkSurfaceCharacterization* characterization = nullptr;
if (characterization_.isValid()) {
sk_sp<SkColorSpace> sk_color_space = color_space.ToSkColorSpace();
if (!SkColorSpace::Equals(characterization_.refColorSpace().get(),
sk_color_space.get())) {
characterization_ = characterization_.createColorSpace(sk_color_space);
}
if (size.width() != characterization_.width() ||
size.height() != characterization_.height()) {
characterization_ =
characterization_.createResized(size.width(), size.height());
}
// TODO(kylechar): Update |characterization_| if |use_alpha| changes.
RecreateRootRecorder();
} else {
characterization = &characterization_;
initialize_waitable_event_ = std::make_unique<base::WaitableEvent>(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
}
auto task = base::BindOnce(&SkiaOutputSurfaceImplOnGpu::Reshape,
base::Unretained(impl_on_gpu_.get()), size,
device_scale_factor, color_space, has_alpha,
use_stencil, pre_transform_, characterization,
initialize_waitable_event_.get());
ScheduleGpuTask(std::move(task), {});
}
| 172,317 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) {
ddjvu_format_t
*format;
ddjvu_page_type_t
type;
Image
*image;
int
ret,
stride;
unsigned char
*q;
ddjvu_rect_t rect;
rect.x = x;
rect.y = y;
rect.w = (unsigned int) w; /* /10 */
rect.h = (unsigned int) h; /* /10 */
image = lc->image;
type = ddjvu_page_get_type(lc->page);
/* stride of this temporary buffer: */
stride = (type == DDJVU_PAGETYPE_BITONAL)?
(image->columns + 7)/8 : image->columns *3;
q = (unsigned char *) AcquireQuantumMemory(image->rows,stride);
if (q == (unsigned char *) NULL)
return;
format = ddjvu_format_create(
(type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24,
/* DDJVU_FORMAT_RGB24
* DDJVU_FORMAT_RGBMASK32*/
/* DDJVU_FORMAT_RGBMASK32 */
0, NULL);
#if 0
/* fixme: ThrowReaderException is a macro, which uses `exception' variable */
if (format == NULL)
{
abort();
/* ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); */
}
#endif
ddjvu_format_set_row_order(format, 1);
ddjvu_format_set_y_direction(format, 1);
ret = ddjvu_page_render(page,
DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */
&rect,
&rect, /* mmc: ?? */
format,
stride, /* ?? */
(char*)q);
(void) ret;
ddjvu_format_release(format);
if (type == DDJVU_PAGETYPE_BITONAL) {
/* */
#if DEBUG
printf("%s: expanding BITONAL page/image\n", __FUNCTION__);
#endif
register IndexPacket *indexes;
size_t bit, byte;
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception);
if (o == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
/* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/
for (x= 0; x < (ssize_t) image->columns; x++)
{
if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)];
if (indexes != (IndexPacket *) NULL)
SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01));
bit++;
if (bit == 8)
bit=0;
byte>>=1;
}
if (SyncAuthenticPixels(image,&image->exception) == MagickFalse)
break;
}
if (!image->ping)
SyncImage(image);
} else {
#if DEBUG
printf("%s: expanding PHOTO page/image\n", __FUNCTION__);
#endif
/* now transfer line-wise: */
ssize_t i;
#if 0
/* old: */
char* r;
#else
register PixelPacket *r;
unsigned char *s;
#endif
s=q;
for (i = 0;i< (ssize_t) image->rows; i++)
{
#if DEBUG
if (i % 1000 == 0) printf("%d\n",i);
#endif
r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(r,ScaleCharToQuantum(*s++));
SetPixelGreen(r,ScaleCharToQuantum(*s++));
SetPixelBlue(r,ScaleCharToQuantum(*s++));
r++;
}
(void) SyncAuthenticPixels(image,&image->exception);
}
}
q=(unsigned char *) RelinquishMagickMemory(q);
}
Commit Message:
CWE ID: CWE-119 | get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) {
ddjvu_format_t
*format;
ddjvu_page_type_t
type;
Image
*image;
int
ret,
stride;
unsigned char
*q;
ddjvu_rect_t rect;
rect.x = x;
rect.y = y;
rect.w = (unsigned int) w; /* /10 */
rect.h = (unsigned int) h; /* /10 */
image = lc->image;
type = ddjvu_page_get_type(lc->page);
/* stride of this temporary buffer: */
stride = (type == DDJVU_PAGETYPE_BITONAL)?
(image->columns + 7)/8 : image->columns *3;
q = (unsigned char *) AcquireQuantumMemory(image->rows,stride);
if (q == (unsigned char *) NULL)
return;
format = ddjvu_format_create(
(type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24,
/* DDJVU_FORMAT_RGB24
* DDJVU_FORMAT_RGBMASK32*/
/* DDJVU_FORMAT_RGBMASK32 */
0, NULL);
#if 0
/* fixme: ThrowReaderException is a macro, which uses `exception' variable */
if (format == NULL)
{
abort();
/* ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); */
}
#endif
ddjvu_format_set_row_order(format, 1);
ddjvu_format_set_y_direction(format, 1);
ret = ddjvu_page_render(page,
DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */
&rect,
&rect, /* mmc: ?? */
format,
stride, /* ?? */
(char*)q);
(void) ret;
ddjvu_format_release(format);
if (type == DDJVU_PAGETYPE_BITONAL) {
/* */
#if DEBUG
printf("%s: expanding BITONAL page/image\n", __FUNCTION__);
#endif
register IndexPacket *indexes;
size_t bit, byte;
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception);
if (o == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
/* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/
for (x= 0; x < (ssize_t) image->columns; x++)
{
if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)];
if (indexes != (IndexPacket *) NULL)
SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01));
bit++;
if (bit == 8)
bit=0;
byte>>=1;
}
if (SyncAuthenticPixels(image,&image->exception) == MagickFalse)
break;
}
if (image->ping == MagickFalse)
SyncImage(image);
} else {
#if DEBUG
printf("%s: expanding PHOTO page/image\n", __FUNCTION__);
#endif
/* now transfer line-wise: */
ssize_t i;
#if 0
/* old: */
char* r;
#else
register PixelPacket *r;
unsigned char *s;
#endif
s=q;
for (i = 0;i< (ssize_t) image->rows; i++)
{
#if DEBUG
if (i % 1000 == 0) printf("%d\n",i);
#endif
r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(r,ScaleCharToQuantum(*s++));
SetPixelGreen(r,ScaleCharToQuantum(*s++));
SetPixelBlue(r,ScaleCharToQuantum(*s++));
r++;
}
(void) SyncAuthenticPixels(image,&image->exception);
}
}
q=(unsigned char *) RelinquishMagickMemory(q);
}
| 168,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: fep_client_open (const char *address)
{
FepClient *client;
struct sockaddr_un sun;
ssize_t sun_len;
int retval;
if (!address)
address = getenv ("LIBFEP_CONTROL_SOCK");
if (!address)
return NULL;
if (strlen (address) + 1 >= sizeof(sun.sun_path))
{
fep_log (FEP_LOG_LEVEL_WARNING,
"unix domain socket path too long: %d + 1 >= %d",
strlen (address),
sizeof (sun.sun_path));
free (address);
return NULL;
}
client = xzalloc (sizeof(FepClient));
client->filter_running = false;
client->messages = NULL;
memset (&sun, 0, sizeof(struct sockaddr_un));
sun.sun_family = AF_UNIX;
#ifdef __linux__
sun.sun_path[0] = '\0';
memcpy (sun.sun_path + 1, address, strlen (address));
sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1;
#else
memcpy (sun.sun_path, address, strlen (address));
sun_len = sizeof (struct sockaddr_un);
#endif
client->control = socket (AF_UNIX, SOCK_STREAM, 0);
if (client->control < 0)
{
free (client);
return NULL;
}
retval = connect (client->control,
(const struct sockaddr *) &sun,
sun_len);
if (retval < 0)
{
close (client->control);
free (client);
return NULL;
}
return client;
}
Commit Message: Don't use abstract Unix domain sockets
CWE ID: CWE-264 | fep_client_open (const char *address)
{
FepClient *client;
struct sockaddr_un sun;
ssize_t sun_len;
int retval;
if (!address)
address = getenv ("LIBFEP_CONTROL_SOCK");
if (!address)
return NULL;
if (strlen (address) + 1 >= sizeof(sun.sun_path))
{
fep_log (FEP_LOG_LEVEL_WARNING,
"unix domain socket path too long: %d + 1 >= %d",
strlen (address),
sizeof (sun.sun_path));
free (address);
return NULL;
}
client = xzalloc (sizeof(FepClient));
client->filter_running = false;
client->messages = NULL;
memset (&sun, 0, sizeof(struct sockaddr_un));
sun.sun_family = AF_UNIX;
memcpy (sun.sun_path, address, strlen (address));
sun_len = sizeof (struct sockaddr_un);
client->control = socket (AF_UNIX, SOCK_STREAM, 0);
if (client->control < 0)
{
free (client);
return NULL;
}
retval = connect (client->control,
(const struct sockaddr *) &sun,
sun_len);
if (retval < 0)
{
close (client->control);
free (client);
return NULL;
}
return client;
}
| 166,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CheckClientDownloadRequest::UploadBinary(
DownloadCheckResult result,
DownloadCheckResultReason reason) {
saved_result_ = result;
saved_reason_ = reason;
bool upload_for_dlp = ShouldUploadForDlpScan();
bool upload_for_malware = ShouldUploadForMalwareScan(reason);
auto request = std::make_unique<DownloadItemRequest>(
item_, /*read_immediately=*/true,
base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete,
weakptr_factory_.GetWeakPtr()));
Profile* profile = Profile::FromBrowserContext(GetBrowserContext());
if (upload_for_dlp) {
DlpDeepScanningClientRequest dlp_request;
dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD);
request->set_request_dlp_scan(std::move(dlp_request));
}
if (upload_for_malware) {
MalwareDeepScanningClientRequest malware_request;
malware_request.set_population(
MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE);
malware_request.set_download_token(
DownloadProtectionService::GetDownloadPingToken(item_));
request->set_request_malware_scan(std::move(malware_request));
}
request->set_dm_token(
policy::BrowserDMTokenStorage::Get()->RetrieveDMToken());
service()->UploadForDeepScanning(profile, std::move(request));
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20 | void CheckClientDownloadRequest::UploadBinary(
DownloadCheckResult result,
DownloadCheckResultReason reason) {
saved_result_ = result;
saved_reason_ = reason;
bool upload_for_dlp = ShouldUploadForDlpScan();
bool upload_for_malware = ShouldUploadForMalwareScan(reason);
auto request = std::make_unique<DownloadItemRequest>(
item_, /*read_immediately=*/true,
base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete,
weakptr_factory_.GetWeakPtr()));
Profile* profile = Profile::FromBrowserContext(GetBrowserContext());
if (upload_for_dlp) {
DlpDeepScanningClientRequest dlp_request;
dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD);
request->set_request_dlp_scan(std::move(dlp_request));
}
if (upload_for_malware) {
MalwareDeepScanningClientRequest malware_request;
malware_request.set_population(
MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE);
malware_request.set_download_token(
DownloadProtectionService::GetDownloadPingToken(item_));
request->set_request_malware_scan(std::move(malware_request));
}
auto dm_token = BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken();
DCHECK(dm_token.is_valid());
request->set_dm_token(dm_token.value());
service()->UploadForDeepScanning(profile, std::move(request));
}
| 172,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FakeCentral::IsPowered() const {
switch (state_) {
case mojom::CentralState::POWERED_OFF:
return false;
case mojom::CentralState::POWERED_ON:
return true;
case mojom::CentralState::ABSENT:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <[email protected]>
Reviewed-by: Giovanni Ortuño Urquidi <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119 | bool FakeCentral::IsPowered() const {
switch (state_) {
case mojom::CentralState::ABSENT:
// SetState() calls IsPowered() to notify observers properly when an adapter
// being removed is simulated, so it should return false.
case mojom::CentralState::POWERED_OFF:
return false;
case mojom::CentralState::POWERED_ON:
return true;
}
NOTREACHED();
return false;
}
| 172,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline struct keydata *get_keyptr(void)
{
struct keydata *keyptr = &ip_keydata[ip_cnt & 1];
smp_rmb();
return keyptr;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static inline struct keydata *get_keyptr(void)
| 165,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error)
return error;
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
Commit Message: xfs: fix two memory leaks in xfs_attr_list.c error paths
This plugs 2 trivial leaks in xfs_attr_shortform_list and
xfs_attr3_leaf_list_int.
Signed-off-by: Mateusz Guzik <[email protected]>
Cc: <[email protected]>
Reviewed-by: Eric Sandeen <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-400 | xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error) {
kmem_free(sbuf);
return error;
}
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
| 166,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LoadingStatsCollectorTest::TestRedirectStatusHistogram(
const std::string& initial_url,
const std::string& prediction_url,
const std::string& navigation_url,
RedirectStatus expected_status) {
const std::string& script_url = "https://cdn.google.com/script.js";
PreconnectPrediction prediction = CreatePreconnectPrediction(
GURL(prediction_url).host(), initial_url != prediction_url,
{{GURL(script_url).GetOrigin(), 1, net::NetworkIsolationKey()}});
EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _))
.WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true)));
std::vector<content::mojom::ResourceLoadInfoPtr> resources;
resources.push_back(
CreateResourceLoadInfoWithRedirects({initial_url, navigation_url}));
resources.push_back(
CreateResourceLoadInfo(script_url, content::ResourceType::kScript));
PageRequestSummary summary =
CreatePageRequestSummary(navigation_url, initial_url, resources);
stats_collector_->RecordPageRequestSummary(summary);
histogram_tester_->ExpectUniqueSample(
internal::kLoadingPredictorPreconnectLearningRedirectStatus,
static_cast<int>(expected_status), 1);
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | void LoadingStatsCollectorTest::TestRedirectStatusHistogram(
const std::string& initial_url,
const std::string& prediction_url,
const std::string& navigation_url,
RedirectStatus expected_status) {
const std::string& script_url = "https://cdn.google.com/script.js";
PreconnectPrediction prediction = CreatePreconnectPrediction(
GURL(prediction_url).host(), initial_url != prediction_url,
{{url::Origin::Create(GURL(script_url)), 1, net::NetworkIsolationKey()}});
EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _))
.WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true)));
std::vector<content::mojom::ResourceLoadInfoPtr> resources;
resources.push_back(
CreateResourceLoadInfoWithRedirects({initial_url, navigation_url}));
resources.push_back(
CreateResourceLoadInfo(script_url, content::ResourceType::kScript));
PageRequestSummary summary =
CreatePageRequestSummary(navigation_url, initial_url, resources);
stats_collector_->RecordPageRequestSummary(summary);
histogram_tester_->ExpectUniqueSample(
internal::kLoadingPredictorPreconnectLearningRedirectStatus,
static_cast<int>(expected_status), 1);
}
| 172,373 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Segment::GetDuration() const
{
assert(m_pInfo);
return m_pInfo->GetDuration();
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Segment::GetDuration() const
| 174,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
assert(m_count == 0);
if (m_preload_count >= cue_points_size) {
const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
CuePoint** const qq = new CuePoint* [n];
CuePoint** q = qq; // beginning of target
CuePoint** p = m_cue_points; // beginning of source
CuePoint** const pp = p + m_preload_count; // end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new CuePoint(m_preload_count, pos);
m_cue_points[m_preload_count++] = pCP;
}
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 | void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
bool Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
if (m_count != 0)
return false;
if (m_preload_count >= cue_points_size) {
const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
CuePoint** const qq = new (std::nothrow) CuePoint*[n];
if (qq == NULL)
return false;
CuePoint** q = qq; // beginning of target
CuePoint** p = m_cue_points; // beginning of source
CuePoint** const pp = p + m_preload_count; // end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new (std::nothrow) CuePoint(m_preload_count, pos);
if (pCP == NULL)
return false;
m_cue_points[m_preload_count++] = pCP;
return true;
}
| 173,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rcomp;
strlcpy(rcomp.type, "compression", sizeof(rcomp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rcomp;
strncpy(rcomp.type, "compression", sizeof(rcomp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
Commit Message: Bug 700947: Add missing ENDTRY opcode in try/catch/finally byte code.
In one of the code branches in handling exceptions in the catch block
we forgot to call the ENDTRY opcode to pop the inner hidden try.
This leads to an unbalanced exception stack which can cause a crash
due to us jumping to a stack frame that has already been exited.
CWE ID: CWE-119 | static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
emit(J, F, OP_ENDTRY);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
| 169,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat)
{
int code = gs_distance_transform_inverse(dx, dy, pmat, pdist);
double rounded;
if (code == gs_error_undefinedresult) {
/* The CTM is degenerate.
Can't know the distance in user space.
} else if (code < 0)
return code;
/* If the distance is very close to integers, round it. */
if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005)
pdist->x = rounded;
if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005)
pdist->y = rounded;
return 0;
}
Commit Message:
CWE ID: CWE-119 | set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat)
{
int code;
double rounded;
if (dx > 1e38 || dy > 1e38)
code = gs_error_undefinedresult;
else
code = gs_distance_transform_inverse(dx, dy, pmat, pdist);
if (code == gs_error_undefinedresult) {
/* The CTM is degenerate.
Can't know the distance in user space.
} else if (code < 0)
return code;
/* If the distance is very close to integers, round it. */
if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005)
pdist->x = rounded;
if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005)
pdist->y = rounded;
return 0;
}
| 164,898 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void lo_release(struct gendisk *disk, fmode_t mode)
{
struct loop_device *lo = disk->private_data;
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
Commit Message: loop: fix concurrent lo_open/lo_release
范龙飞 reports that KASAN can report a use-after-free in __lock_acquire.
The reason is due to insufficient serialization in lo_release(), which
will continue to use the loop device even after it has decremented the
lo_refcnt to zero.
In the meantime, another process can come in, open the loop device
again as it is being shut down. Confusion ensues.
Reported-by: 范龙飞 <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416 | static void lo_release(struct gendisk *disk, fmode_t mode)
static void __lo_release(struct loop_device *lo)
{
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
| 169,352 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetInputMethodLibrary(
InputMethodLibrary* library, bool own) {
library_->input_method_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::SetInputMethodLibrary(
| 170,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SynchronousCompositorOutputSurface::InvokeComposite(
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
gfx::Transform transform_for_tile_priority,
bool hardware_draw) {
DCHECK(!frame_holder_.get());
gfx::Transform adjusted_transform = transform;
adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0);
SetExternalDrawConstraints(adjusted_transform, viewport, clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority, !hardware_draw);
if (!hardware_draw || next_hardware_draw_needs_damage_) {
next_hardware_draw_needs_damage_ = false;
SetNeedsRedrawRect(gfx::Rect(viewport.size()));
}
client_->OnDraw();
if (hardware_draw) {
cached_hw_transform_ = adjusted_transform;
cached_hw_viewport_ = viewport;
cached_hw_clip_ = clip;
cached_hw_viewport_rect_for_tile_priority_ =
viewport_rect_for_tile_priority;
cached_hw_transform_for_tile_priority_ = transform_for_tile_priority;
} else {
bool resourceless_software_draw = false;
SetExternalDrawConstraints(cached_hw_transform_,
cached_hw_viewport_,
cached_hw_clip_,
cached_hw_viewport_rect_for_tile_priority_,
cached_hw_transform_for_tile_priority_,
resourceless_software_draw);
next_hardware_draw_needs_damage_ = true;
}
if (frame_holder_.get())
client_->DidSwapBuffersComplete();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void SynchronousCompositorOutputSurface::InvokeComposite(
const gfx::Transform& transform,
const gfx::Rect& viewport,
const gfx::Rect& clip,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority,
bool hardware_draw) {
DCHECK(!frame_holder_.get());
gfx::Transform adjusted_transform = transform;
adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0);
SetExternalDrawConstraints(adjusted_transform, viewport, clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority, !hardware_draw);
if (!hardware_draw || next_hardware_draw_needs_damage_) {
next_hardware_draw_needs_damage_ = false;
SetNeedsRedrawRect(gfx::Rect(viewport.size()));
}
client_->OnDraw();
if (hardware_draw) {
cached_hw_transform_ = adjusted_transform;
cached_hw_viewport_ = viewport;
cached_hw_clip_ = clip;
cached_hw_viewport_rect_for_tile_priority_ =
viewport_rect_for_tile_priority;
cached_hw_transform_for_tile_priority_ = transform_for_tile_priority;
} else {
bool resourceless_software_draw = false;
SetExternalDrawConstraints(cached_hw_transform_,
cached_hw_viewport_,
cached_hw_clip_,
cached_hw_viewport_rect_for_tile_priority_,
cached_hw_transform_for_tile_priority_,
resourceless_software_draw);
next_hardware_draw_needs_damage_ = true;
}
if (frame_holder_.get())
client_->DidSwapBuffersComplete();
}
| 171,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ID3::Iterator::getstring(String8 *id, bool otherdata) const {
id->setTo("");
const uint8_t *frameData = mFrameData;
if (frameData == NULL) {
return;
}
uint8_t encoding = *frameData;
if (mParent.mVersion == ID3_V1 || mParent.mVersion == ID3_V1_1) {
if (mOffset == 126 || mOffset == 127) {
char tmp[16];
sprintf(tmp, "%d", (int)*frameData);
id->setTo(tmp);
return;
}
id->setTo((const char*)frameData, mFrameSize);
return;
}
if (mFrameSize < getHeaderLength() + 1) {
return;
}
size_t n = mFrameSize - getHeaderLength() - 1;
if (otherdata) {
frameData += 4;
int32_t i = n - 4;
while(--i >= 0 && *++frameData != 0) ;
int skipped = (frameData - mFrameData);
if (skipped >= (int)n) {
return;
}
n -= skipped;
}
if (encoding == 0x00) {
id->setTo((const char*)frameData + 1, n);
} else if (encoding == 0x03) {
id->setTo((const char *)(frameData + 1), n);
} else if (encoding == 0x02) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
#if BYTE_ORDER == LITTLE_ENDIAN
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
#endif
id->setTo(framedata, len);
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
} else if (encoding == 0x01) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
if (*framedata == 0xfffe) {
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
}
if (*framedata == 0xfeff) {
framedata++;
len--;
}
bool eightBit = true;
for (int i = 0; i < len; i++) {
if (framedata[i] > 0xff) {
eightBit = false;
break;
}
}
if (eightBit) {
char *frame8 = new char[len];
for (int i = 0; i < len; i++) {
frame8[i] = framedata[i];
}
id->setTo(frame8, len);
delete [] frame8;
} else {
id->setTo(framedata, len);
}
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
}
}
Commit Message: better validation lengths of strings in ID3 tags
Validate lengths on strings in ID3 tags, particularly around 0.
Also added code to handle cases when we can't get memory for
copies of strings we want to extract from these tags.
Affects L/M/N/master, same patch for all of them.
Bug: 30744884
Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e
Test: play mp3 file which caused a <0 length.
(cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f)
CWE ID: CWE-20 | void ID3::Iterator::getstring(String8 *id, bool otherdata) const {
id->setTo("");
const uint8_t *frameData = mFrameData;
if (frameData == NULL) {
return;
}
uint8_t encoding = *frameData;
if (mParent.mVersion == ID3_V1 || mParent.mVersion == ID3_V1_1) {
if (mOffset == 126 || mOffset == 127) {
char tmp[16];
sprintf(tmp, "%d", (int)*frameData);
id->setTo(tmp);
return;
}
id->setTo((const char*)frameData, mFrameSize);
return;
}
if (mFrameSize < getHeaderLength() + 1) {
return;
}
size_t n = mFrameSize - getHeaderLength() - 1;
if (otherdata) {
frameData += 4;
int32_t i = n - 4;
while(--i >= 0 && *++frameData != 0) ;
int skipped = (frameData - mFrameData);
if (skipped >= (int)n) {
return;
}
n -= skipped;
}
if (n <= 0) {
return;
}
if (encoding == 0x00) {
id->setTo((const char*)frameData + 1, n);
} else if (encoding == 0x03) {
id->setTo((const char *)(frameData + 1), n);
} else if (encoding == 0x02) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
#if BYTE_ORDER == LITTLE_ENDIAN
if (len > 0) {
framedatacopy = new (std::nothrow) char16_t[len];
if (framedatacopy == NULL) {
return;
}
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
}
#endif
id->setTo(framedata, len);
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
} else if (encoding == 0x01) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
if (*framedata == 0xfffe) {
// endianness marker != host endianness, convert & skip
if (len <= 1) {
return; // nothing after the marker
}
framedatacopy = new (std::nothrow) char16_t[len];
if (framedatacopy == NULL) {
return;
}
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
// and skip over the marker
framedata++;
len--;
} else if (*framedata == 0xfeff) {
// endianness marker == host endianness, skip it
if (len <= 1) {
return; // nothing after the marker
}
framedata++;
len--;
}
bool eightBit = true;
for (int i = 0; i < len; i++) {
if (framedata[i] > 0xff) {
eightBit = false;
break;
}
}
if (eightBit) {
char *frame8 = new (std::nothrow) char[len];
if (frame8 != NULL) {
for (int i = 0; i < len; i++) {
frame8[i] = framedata[i];
}
id->setTo(frame8, len);
delete [] frame8;
} else {
id->setTo(framedata, len);
}
} else {
id->setTo(framedata, len);
}
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
}
}
| 173,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin)
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
numones = CLIP3(numones, 0, 16);
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
Commit Message: Fix in handling wrong cu_qp_delta
cu_qp_delta is now checked for the range as specified in the spec
Bug: 33966031
Change-Id: I00420bf68081af92e9f2be9af7ce58d0683094ca
CWE ID: CWE-119 | UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin && (numones <= 16))
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
| 174,051 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MessageLoop::NestableTasksAllowed() const {
return nestable_tasks_allowed_;
}
Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower.
(as well as MessageLoop::SetNestableTasksAllowed())
Surveying usage: the scoped object is always instantiated right before
RunLoop().Run(). The intent is really to allow nestable tasks in that
RunLoop so it's better to explicitly label that RunLoop as such and it
allows us to break the last dependency that forced some RunLoop users
to use MessageLoop APIs.
There's also the odd case of allowing nestable tasks for loops that are
reentrant from a native task (without going through RunLoop), these
are the minority but will have to be handled (after cleaning up the
majority of cases that are RunLoop induced).
As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517
(which was merged in this CL).
[email protected]
Bug: 750779
Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448
Reviewed-on: https://chromium-review.googlesource.com/594713
Commit-Queue: Gabriel Charette <[email protected]>
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: danakj <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492263}
CWE ID: | bool MessageLoop::NestableTasksAllowed() const {
return nestable_tasks_allowed_ || run_loop_client_->ProcessingTasksAllowed();
}
| 171,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeMetricsServiceClient::RegisterUKMProviders() {
ukm_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
#if defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
#endif // !defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<variations::FieldTrialsProvider>(nullptr,
kUKMFieldTrialSuffix));
}
Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM.
Bug: 907674
Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2
Reviewed-on: https://chromium-review.googlesource.com/c/1381376
Commit-Queue: Nik Bhagat <[email protected]>
Reviewed-by: Robert Kaplow <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618037}
CWE ID: CWE-79 | void ChromeMetricsServiceClient::RegisterUKMProviders() {
ukm_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
#if defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
#endif // !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::GPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::CPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ScreenInfoMetricsProvider>());
ukm_service_->RegisterMetricsProvider(
std::make_unique<variations::FieldTrialsProvider>(nullptr,
kUKMFieldTrialSuffix));
}
| 172,071 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] Avoid index out of bounds access to pi->include[]
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-20 | static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
| 169,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IPV6DefragReverseSimpleTest(void)
{
DefragContext *dc = NULL;
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | IPV6DefragReverseSimpleTest(void)
{
DefragContext *dc = NULL;
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
dc = DefragContextNew();
if (dc == NULL)
goto end;
p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (dc != NULL)
DefragContextDestroy(dc);
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
| 168,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out)
{
struct sc_path path;
struct sc_file *tmp_file = NULL;
size_t offs, ii;
int rv;
LOG_FUNC_CALLED(card->ctx);
assert(card != NULL && in_path != NULL);
memcpy(&path, in_path, sizeof(struct sc_path));
sc_log(card->ctx, "in_path; type=%d, path=%s, out %p",
in_path->type, sc_print_path(in_path), file_out);
sc_log(card->ctx, "current path; type=%d, path=%s",
auth_current_df->path.type, sc_print_path(&auth_current_df->path));
if (auth_current_ef)
sc_log(card->ctx, "current file; type=%d, path=%s",
auth_current_ef->path.type, sc_print_path(&auth_current_ef->path));
if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
rv = iso_ops->select_file(card, &path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select file failed");
if (!tmp_file)
return SC_ERROR_OBJECT_NOT_FOUND;
if (path.type == SC_PATH_TYPE_PARENT) {
memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));
if (tmp_file->path.len > 2)
tmp_file->path.len -= 2;
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
if (tmp_file->type == SC_FILE_TYPE_DF) {
sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, tmp_file);
sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);
}
}
if (file_out)
sc_file_dup(file_out, tmp_file);
sc_file_free(tmp_file);
}
else if (path.type == SC_PATH_TYPE_DF_NAME) {
rv = iso_ops->select_file(card, &path, NULL);
if (rv) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
}
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
else {
for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)
if (path.value[offs] != auth_current_df->path.value[offs] ||
path.value[offs + 1] != auth_current_df->path.value[offs + 1])
break;
sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs);
if (offs && offs < auth_current_df->path.len) {
size_t deep = auth_current_df->path.len - offs;
sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u",
deep);
for (ii=0; ii<deep; ii+=2) {
struct sc_path tmp_path;
memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file (card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
if (path.len - offs > 0) {
struct sc_path tmp_path;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
for (ii=0; ii < path.len - offs; ii+=2) {
memcpy(tmp_path.value, path.value + offs + ii, 2);
rv = auth_select_file(card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
else if (path.len - offs == 0 && file_out) {
if (sc_compare_path(&path, &auth_current_df->path))
sc_file_dup(file_out, auth_current_df);
else if (auth_current_ef)
sc_file_dup(file_out, auth_current_ef);
else
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF");
}
}
LOG_FUNC_RETURN(card->ctx, 0);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out)
{
struct sc_path path;
struct sc_file *tmp_file = NULL;
size_t offs, ii;
int rv;
LOG_FUNC_CALLED(card->ctx);
assert(card != NULL && in_path != NULL);
memcpy(&path, in_path, sizeof(struct sc_path));
if (!auth_current_df)
return SC_ERROR_OBJECT_NOT_FOUND;
sc_log(card->ctx, "in_path; type=%d, path=%s, out %p",
in_path->type, sc_print_path(in_path), file_out);
sc_log(card->ctx, "current path; type=%d, path=%s",
auth_current_df->path.type, sc_print_path(&auth_current_df->path));
if (auth_current_ef)
sc_log(card->ctx, "current file; type=%d, path=%s",
auth_current_ef->path.type, sc_print_path(&auth_current_ef->path));
if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
rv = iso_ops->select_file(card, &path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select file failed");
if (!tmp_file)
return SC_ERROR_OBJECT_NOT_FOUND;
if (path.type == SC_PATH_TYPE_PARENT) {
memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));
if (tmp_file->path.len > 2)
tmp_file->path.len -= 2;
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
if (tmp_file->type == SC_FILE_TYPE_DF) {
sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, tmp_file);
sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);
}
}
if (file_out)
sc_file_dup(file_out, tmp_file);
sc_file_free(tmp_file);
}
else if (path.type == SC_PATH_TYPE_DF_NAME) {
rv = iso_ops->select_file(card, &path, NULL);
if (rv) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
}
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
else {
for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)
if (path.value[offs] != auth_current_df->path.value[offs] ||
path.value[offs + 1] != auth_current_df->path.value[offs + 1])
break;
sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs);
if (offs && offs < auth_current_df->path.len) {
size_t deep = auth_current_df->path.len - offs;
sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u",
deep);
for (ii=0; ii<deep; ii+=2) {
struct sc_path tmp_path;
memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file (card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
if (path.len - offs > 0) {
struct sc_path tmp_path;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
for (ii=0; ii < path.len - offs; ii+=2) {
memcpy(tmp_path.value, path.value + offs + ii, 2);
rv = auth_select_file(card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
else if (path.len - offs == 0 && file_out) {
if (sc_compare_path(&path, &auth_current_df->path))
sc_file_dup(file_out, auth_current_df);
else if (auth_current_ef)
sc_file_dup(file_out, auth_current_ef);
else
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF");
}
}
LOG_FUNC_RETURN(card->ctx, 0);
}
| 169,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool CSPSource::schemeMatches(const KURL& url) const
{
if (m_scheme.isEmpty())
return m_policy->protocolMatchesSelf(url);
return equalIgnoringCase(url.protocol(), m_scheme);
}
Commit Message: CSP: Source expressions can no longer lock sites into insecurity.
CSP's matching algorithm has been updated to make clever folks like Yan
slightly less able to gather data on user's behavior based on CSP
reports[1]. This matches Firefox's existing behavior (they apparently
changed this behavior a few months ago, via a happy accident[2]), and
mitigates the CSP-variant of Sniffly[3].
On the dashboard at https://www.chromestatus.com/feature/6653486812889088.
[1]: https://github.com/w3c/webappsec-csp/commit/0e81d81b64c42ca3c81c048161162b9697ff7b60
[2]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218524#c2
[3]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218778#c7
BUG=544765,558232
Review URL: https://codereview.chromium.org/1455973003
Cr-Commit-Position: refs/heads/master@{#360562}
CWE ID: CWE-200 | bool CSPSource::schemeMatches(const KURL& url) const
{
if (m_scheme.isEmpty())
return m_policy->protocolMatchesSelf(url);
if (equalIgnoringCase(m_scheme, "http"))
return equalIgnoringCase(url.protocol(), "http") || equalIgnoringCase(url.protocol(), "https");
if (equalIgnoringCase(m_scheme, "ws"))
return equalIgnoringCase(url.protocol(), "ws") || equalIgnoringCase(url.protocol(), "wss");
return equalIgnoringCase(url.protocol(), m_scheme);
}
| 172,237 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetTouchpadLibrary(
TouchpadLibrary* library, bool own) {
library_->touchpad_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::SetTouchpadLibrary(
| 170,648 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX::buffer_id OMXNodeInstance::findBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
return (OMX::buffer_id)bufferHeader;
}
Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32
Bug: 20634516
Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c
(cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4)
CWE ID: CWE-119 | OMX::buffer_id OMXNodeInstance::findBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
| 173,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void hostap_setup_dev(struct net_device *dev, local_info_t *local,
int type)
{
struct hostap_interface *iface;
iface = netdev_priv(dev);
ether_setup(dev);
/* kernel callbacks */
if (iface) {
/* Currently, we point to the proper spy_data only on
* the main_dev. This could be fixed. Jean II */
iface->wireless_data.spy_data = &iface->spy_data;
dev->wireless_data = &iface->wireless_data;
}
dev->wireless_handlers = &hostap_iw_handler_def;
dev->watchdog_timeo = TX_TIMEOUT;
switch(type) {
case HOSTAP_INTERFACE_AP:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_mgmt_netdev_ops;
dev->type = ARPHRD_IEEE80211;
dev->header_ops = &hostap_80211_ops;
break;
case HOSTAP_INTERFACE_MASTER:
dev->netdev_ops = &hostap_master_ops;
break;
default:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_netdev_ops;
}
dev->mtu = local->mtu;
SET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | void hostap_setup_dev(struct net_device *dev, local_info_t *local,
int type)
{
struct hostap_interface *iface;
iface = netdev_priv(dev);
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
/* kernel callbacks */
if (iface) {
/* Currently, we point to the proper spy_data only on
* the main_dev. This could be fixed. Jean II */
iface->wireless_data.spy_data = &iface->spy_data;
dev->wireless_data = &iface->wireless_data;
}
dev->wireless_handlers = &hostap_iw_handler_def;
dev->watchdog_timeo = TX_TIMEOUT;
switch(type) {
case HOSTAP_INTERFACE_AP:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_mgmt_netdev_ops;
dev->type = ARPHRD_IEEE80211;
dev->header_ops = &hostap_80211_ops;
break;
case HOSTAP_INTERFACE_MASTER:
dev->netdev_ops = &hostap_master_ops;
break;
default:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_netdev_ops;
}
dev->mtu = local->mtu;
SET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);
}
| 165,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::GetNumber() const
{
return m_info.number;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Track::GetNumber() const
| 174,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Enable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_enable, event);
return;
}
raw_spin_lock_irq(&ctx->lock);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto out;
/*
* If the event is in error state, clear that first.
* That way, if we see the event in error state below, we
* know that it has gone back into error state, as distinct
* from the task having been scheduled away before the
* cross-call arrived.
*/
if (event->state == PERF_EVENT_STATE_ERROR)
event->state = PERF_EVENT_STATE_OFF;
retry:
if (!ctx->is_active) {
__perf_event_mark_enabled(event);
goto out;
}
raw_spin_unlock_irq(&ctx->lock);
if (!task_function_call(task, __perf_event_enable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the context is active and the event is still off,
* we need to retry the cross-call.
*/
if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
/*
* task could have been flipped by a concurrent
* perf_event_context_sched_out()
*/
task = ctx->task;
goto retry;
}
out:
raw_spin_unlock_irq(&ctx->lock);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | void perf_event_enable(struct perf_event *event)
static void _perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Enable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_enable, event);
return;
}
raw_spin_lock_irq(&ctx->lock);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto out;
/*
* If the event is in error state, clear that first.
* That way, if we see the event in error state below, we
* know that it has gone back into error state, as distinct
* from the task having been scheduled away before the
* cross-call arrived.
*/
if (event->state == PERF_EVENT_STATE_ERROR)
event->state = PERF_EVENT_STATE_OFF;
retry:
if (!ctx->is_active) {
__perf_event_mark_enabled(event);
goto out;
}
raw_spin_unlock_irq(&ctx->lock);
if (!task_function_call(task, __perf_event_enable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the context is active and the event is still off,
* we need to retry the cross-call.
*/
if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
/*
* task could have been flipped by a concurrent
* perf_event_context_sched_out()
*/
task = ctx->task;
goto retry;
}
out:
raw_spin_unlock_irq(&ctx->lock);
}
| 166,983 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit HeaderTestDispatcherHostDelegate(const GURL& watch_url)
: watch_url_(watch_url) {}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | explicit HeaderTestDispatcherHostDelegate(const GURL& watch_url)
explicit ThrottleContentBrowserClient(const GURL& watch_url)
: watch_url_(watch_url) {}
| 172,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
unsigned numEntries = darray_size(append->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, numEntries);
darray_concat(expr->keysym_list.syms, append->keysym_list.syms);
FreeStmt((ParseCommon *) &append);
return expr;
}
Commit Message: xkbcomp: fix pointer value for FreeStmt
Signed-off-by: Peter Hutterer <[email protected]>
CWE ID: CWE-416 | ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
unsigned numEntries = darray_size(append->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, numEntries);
darray_concat(expr->keysym_list.syms, append->keysym_list.syms);
FreeStmt((ParseCommon *) append);
return expr;
}
| 169,093 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.