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: bgp_attr_unknown (struct bgp_attr_parser_args *args)
{
bgp_size_t total;
struct transit *transit;
struct attr_extra *attre;
struct peer *const peer = args->peer;
struct attr *const attr = args->attr;
u_char *const startp = args->startp;
const u_char type = args->type;
const u_char flag = args->flags;
const bgp_size_t length = args->length;
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s Unknown attribute is received (type %d, length %d)",
peer->host, type, length);
if (BGP_DEBUG (events, EVENTS))
zlog (peer->log, LOG_DEBUG,
"Unknown attribute type %d length %d is received", type, length);
/* Forward read pointer of input stream. */
stream_forward_getp (peer->ibuf, length);
/* If any of the mandatory well-known attributes are not recognized,
then the Error Subcode is set to Unrecognized Well-known
Attribute. The Data field contains the unrecognized attribute
(type, length and value). */
if (!CHECK_FLAG (flag, BGP_ATTR_FLAG_OPTIONAL))
{
return bgp_attr_malformed (args,
BGP_NOTIFY_UPDATE_UNREC_ATTR,
args->total);
}
/* Unrecognized non-transitive optional attributes must be quietly
ignored and not passed along to other BGP peers. */
if (! CHECK_FLAG (flag, BGP_ATTR_FLAG_TRANS))
return BGP_ATTR_PARSE_PROCEED;
/* If a path with recognized transitive optional attribute is
accepted and passed along to other BGP peers and the Partial bit
in the Attribute Flags octet is set to 1 by some previous AS, it
is not set back to 0 by the current AS. */
SET_FLAG (*startp, BGP_ATTR_FLAG_PARTIAL);
/* Store transitive attribute to the end of attr->transit. */
if (! ((attre = bgp_attr_extra_get(attr))->transit) )
attre->transit = XCALLOC (MTYPE_TRANSIT, sizeof (struct transit));
transit = attre->transit;
if (transit->val)
transit->val = XREALLOC (MTYPE_TRANSIT_VAL, transit->val,
transit->length + total);
else
transit->val = XMALLOC (MTYPE_TRANSIT_VAL, total);
memcpy (transit->val + transit->length, startp, total);
transit->length += total;
return BGP_ATTR_PARSE_PROCEED;
}
Commit Message:
CWE ID: | bgp_attr_unknown (struct bgp_attr_parser_args *args)
{
bgp_size_t total = args->total;
struct transit *transit;
struct attr_extra *attre;
struct peer *const peer = args->peer;
struct attr *const attr = args->attr;
u_char *const startp = args->startp;
const u_char type = args->type;
const u_char flag = args->flags;
const bgp_size_t length = args->length;
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s Unknown attribute is received (type %d, length %d)",
peer->host, type, length);
if (BGP_DEBUG (events, EVENTS))
zlog (peer->log, LOG_DEBUG,
"Unknown attribute type %d length %d is received", type, length);
/* Forward read pointer of input stream. */
stream_forward_getp (peer->ibuf, length);
/* If any of the mandatory well-known attributes are not recognized,
then the Error Subcode is set to Unrecognized Well-known
Attribute. The Data field contains the unrecognized attribute
(type, length and value). */
if (!CHECK_FLAG (flag, BGP_ATTR_FLAG_OPTIONAL))
{
return bgp_attr_malformed (args,
BGP_NOTIFY_UPDATE_UNREC_ATTR,
args->total);
}
/* Unrecognized non-transitive optional attributes must be quietly
ignored and not passed along to other BGP peers. */
if (! CHECK_FLAG (flag, BGP_ATTR_FLAG_TRANS))
return BGP_ATTR_PARSE_PROCEED;
/* If a path with recognized transitive optional attribute is
accepted and passed along to other BGP peers and the Partial bit
in the Attribute Flags octet is set to 1 by some previous AS, it
is not set back to 0 by the current AS. */
SET_FLAG (*startp, BGP_ATTR_FLAG_PARTIAL);
/* Store transitive attribute to the end of attr->transit. */
if (! ((attre = bgp_attr_extra_get(attr))->transit) )
attre->transit = XCALLOC (MTYPE_TRANSIT, sizeof (struct transit));
transit = attre->transit;
if (transit->val)
transit->val = XREALLOC (MTYPE_TRANSIT_VAL, transit->val,
transit->length + total);
else
transit->val = XMALLOC (MTYPE_TRANSIT_VAL, total);
memcpy (transit->val + transit->length, startp, total);
transit->length += total;
return BGP_ATTR_PARSE_PROCEED;
}
| 164,575 |
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::Rect ShellWindowFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
return gfx::Rect(client_bounds.x(),
std::max(0, client_bounds.y() - kCaptionHeight),
std::max(header_width, client_bounds.width()),
client_bounds.height() + kCaptionHeight);
}
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::Rect ShellWindowFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
if (is_frameless_)
return client_bounds;
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
return gfx::Rect(client_bounds.x(),
std::max(0, client_bounds.y() - kCaptionHeight),
std::max(header_width, client_bounds.width()),
client_bounds.height() + kCaptionHeight);
}
| 170,714 |
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 PageHandler::PrintToPDF(Maybe<bool> landscape,
Maybe<bool> display_header_footer,
Maybe<bool> print_background,
Maybe<double> scale,
Maybe<double> paper_width,
Maybe<double> paper_height,
Maybe<double> margin_top,
Maybe<double> margin_bottom,
Maybe<double> margin_left,
Maybe<double> margin_right,
Maybe<String> page_ranges,
Maybe<bool> ignore_invalid_page_ranges,
std::unique_ptr<PrintToPDFCallback> callback) {
callback->sendFailure(Response::Error("PrintToPDF is not implemented"));
return;
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Jianzhou Feng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20 | void PageHandler::PrintToPDF(Maybe<bool> landscape,
Maybe<bool> display_header_footer,
Maybe<bool> print_background,
Maybe<double> scale,
Maybe<double> paper_width,
Maybe<double> paper_height,
Maybe<double> margin_top,
Maybe<double> margin_bottom,
Maybe<double> margin_left,
Maybe<double> margin_right,
Maybe<String> page_ranges,
Maybe<bool> ignore_invalid_page_ranges,
Maybe<String> header_template,
Maybe<String> footer_template,
std::unique_ptr<PrintToPDFCallback> callback) {
callback->sendFailure(Response::Error("PrintToPDF is not implemented"));
return;
}
| 172,900 |
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 x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
Commit Message: net: fix a kernel infoleak in x25 module
Stack object "dte_facilities" is allocated in x25_rx_call_request(),
which is supposed to be initialized in x25_negotiate_facilities.
However, 5 fields (8 bytes in total) are not initialized. This
object is then copied to userland via copy_to_user, thus infoleak
occurs.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
memset(dte, 0, sizeof(*dte));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
| 167,235 |
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 iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *out_csdescr)
{
int i,j;
int z;
int k;
int retval=0;
iw_tmpsample tmpsamp;
iw_tmpsample alphasamp = 0.0;
iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples
iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples
int using_errdiffdither = 0;
int output_channel;
int is_alpha_channel;
int bkgd_has_transparency;
double tmpbkgdalpha=0.0;
int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample
struct iw_resize_settings *rs = NULL;
int ditherfamily, dithersubtype;
struct iw_channelinfo_intermed *int_ci;
struct iw_channelinfo_out *out_ci;
iw_tmpsample *in_pix = NULL;
iw_tmpsample *out_pix = NULL;
int num_in_pix;
int num_out_pix;
num_in_pix = ctx->intermed_canvas_width;
num_out_pix = ctx->img2.width;
int_ci = &ctx->intermed_ci[intermed_channel];
output_channel = int_ci->corresponding_output_channel;
out_ci = &ctx->img2_ci[output_channel];
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
bkgd_has_transparency = iw_bkgd_has_transparency(ctx);
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
in_pix = inpix_tofree;
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
if(ctx->nearest_color_table && !is_alpha_channel &&
out_ci->ditherfamily==IW_DITHERFAMILY_NONE &&
out_ci->color_count==0)
{
out_ci->use_nearest_color_table = 1;
}
else {
out_ci->use_nearest_color_table = 0;
}
ditherfamily = out_ci->ditherfamily;
dithersubtype = out_ci->dithersubtype;
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA)
{
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed);
}
else {
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype);
}
}
if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
using_errdiffdither = 1;
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k][i] = 0.0;
}
}
}
rs=&ctx->resize_settings[IW_DIMENSION_H];
if(!rs->rrctx) {
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(j=0;j<ctx->intermed_canvas_height;j++) {
if(is_alpha_channel) {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
else {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) {
for(i=0;i<num_out_pix;i++) {
ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i];
}
}
if(output_channel == -1) {
goto here;
}
for(z=0;z<ctx->img2.width;z++) {
if(using_errdiffdither && (j%2))
i=ctx->img2.width-1-z;
else
i=z;
tmpsamp = out_pix[i];
if(ctx->bkgd_checkerboard) {
alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) !=
(((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2);
}
if(bkgd_has_transparency) {
tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha;
}
if(int_ci->need_unassoc_alpha_processing) {
alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i];
if(alphasamp!=0.0) {
tmpsamp /= alphasamp;
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) {
double bkcolor;
bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin;
if(bkgd_has_transparency) {
tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp);
}
else {
tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp);
}
}
}
else if(is_alpha_channel && bkgd_has_transparency) {
tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp);
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr);
else
put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr);
}
if(using_errdiffdither) {
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS-1;k++) {
ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i];
}
ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0;
}
}
here:
;
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
Commit Message: Fixed a bug that could cause invalid memory to be accessed
The bug could happen when transparency is removed from an image.
Also fixed a semi-related BMP error handling logic bug.
Fixes issue #21
CWE ID: CWE-787 | static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *out_csdescr)
{
int i,j;
int z;
int k;
int retval=0;
iw_tmpsample tmpsamp;
iw_tmpsample alphasamp = 0.0;
iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples
iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples
int using_errdiffdither = 0;
int output_channel;
int is_alpha_channel;
int bkgd_has_transparency;
double tmpbkgdalpha=0.0;
int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample
struct iw_resize_settings *rs = NULL;
int ditherfamily, dithersubtype;
struct iw_channelinfo_intermed *int_ci;
struct iw_channelinfo_out *out_ci;
iw_tmpsample *in_pix = NULL;
iw_tmpsample *out_pix = NULL;
int num_in_pix;
int num_out_pix;
struct iw_channelinfo_out default_ci_out;
num_in_pix = ctx->intermed_canvas_width;
num_out_pix = ctx->img2.width;
int_ci = &ctx->intermed_ci[intermed_channel];
output_channel = int_ci->corresponding_output_channel;
if(output_channel>=0) {
out_ci = &ctx->img2_ci[output_channel];
}
else {
// If there is no output channelinfo struct, create a temporary one to
// use.
// TODO: This is admittedly ugly, but we use these settings for a few
// things even when there is no corresponding output channel, and I
// don't remember exactly why.
iw_zeromem(&default_ci_out, sizeof(struct iw_channelinfo_out));
default_ci_out.channeltype = IW_CHANNELTYPE_NONALPHA;
out_ci = &default_ci_out;
}
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
bkgd_has_transparency = iw_bkgd_has_transparency(ctx);
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
in_pix = inpix_tofree;
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
if(ctx->nearest_color_table && !is_alpha_channel &&
out_ci->ditherfamily==IW_DITHERFAMILY_NONE &&
out_ci->color_count==0)
{
out_ci->use_nearest_color_table = 1;
}
else {
out_ci->use_nearest_color_table = 0;
}
ditherfamily = out_ci->ditherfamily;
dithersubtype = out_ci->dithersubtype;
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA)
{
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed);
}
else {
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype);
}
}
if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
using_errdiffdither = 1;
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k][i] = 0.0;
}
}
}
rs=&ctx->resize_settings[IW_DIMENSION_H];
if(!rs->rrctx) {
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(j=0;j<ctx->intermed_canvas_height;j++) {
if(is_alpha_channel) {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
else {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) {
for(i=0;i<num_out_pix;i++) {
ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i];
}
}
if(output_channel == -1) {
goto here;
}
for(z=0;z<ctx->img2.width;z++) {
if(using_errdiffdither && (j%2))
i=ctx->img2.width-1-z;
else
i=z;
tmpsamp = out_pix[i];
if(ctx->bkgd_checkerboard) {
alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) !=
(((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2);
}
if(bkgd_has_transparency) {
tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha;
}
if(int_ci->need_unassoc_alpha_processing) {
alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i];
if(alphasamp!=0.0) {
tmpsamp /= alphasamp;
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) {
double bkcolor;
bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin;
if(bkgd_has_transparency) {
tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp);
}
else {
tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp);
}
}
}
else if(is_alpha_channel && bkgd_has_transparency) {
tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp);
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr);
else
put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr);
}
if(using_errdiffdither) {
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS-1;k++) {
ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i];
}
ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0;
}
}
here:
;
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
| 168,118 |
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 VRDisplay::OnFocus() {
display_blurred_ = false;
ConnectVSyncProvider();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayfocus, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnFocus() {
DVLOG(1) << __FUNCTION__;
display_blurred_ = false;
ConnectVSyncProvider();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayfocus, true, false, this, ""));
}
| 171,995 |
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: ext2_xattr_cache_insert(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext2_xattr_cache, GFP_NOFS);
if (!ce)
return -ENOMEM;
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache (%d cache entries)",
atomic_read(&ext2_xattr_cache->c_entry_count));
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x] (%d cache entries)", (int)hash,
atomic_read(&ext2_xattr_cache->c_entry_count));
mb_cache_entry_release(ce);
}
return error;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_cache_insert(struct buffer_head *bh)
ext2_xattr_cache_insert(struct mb2_cache *cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
int error;
error = mb2_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr);
if (error) {
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache (%d cache entries)",
atomic_read(&ext2_xattr_cache->c_entry_count));
error = 0;
}
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
return error;
}
| 169,978 |
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 rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
Commit Message: Bluetooth: RFCOMM - Fix missing msg_namelen update in rfcomm_sock_recvmsg()
If RFCOMM_DEFER_SETUP is set in the flags, rfcomm_sock_recvmsg() returns
early with 0 without updating the possibly set msg_namelen member. This,
in turn, leads to a 128 byte kernel stack leak in net/socket.c.
Fix this by updating msg_namelen in this case. For all other cases it
will be handled in bt_sock_stream_recvmsg().
Cc: Marcel Holtmann <[email protected]>
Cc: Gustavo Padovan <[email protected]>
Cc: Johan Hedberg <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
msg->msg_namelen = 0;
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
| 166,042 |
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 setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
{
path->incReserve(numPoints);
path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
WebCoreFloatToSkScalar(points[0].y()));
for (size_t i = 1; i < numPoints; ++i) {
path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
WebCoreFloatToSkScalar(points[i].y()));
}
path->setIsConvex(true);
}
Commit Message: [skia] not all convex paths are convex, so recompute convexity for the problematic ones
https://bugs.webkit.org/show_bug.cgi?id=75960
Reviewed by Stephen White.
No new tests.
See related chrome issue
http://code.google.com/p/chromium/issues/detail?id=108605
* platform/graphics/skia/GraphicsContextSkia.cpp:
(WebCore::setPathFromConvexPoints):
git-svn-id: svn://svn.chromium.org/blink/trunk@104609 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-19 | static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
{
path->incReserve(numPoints);
path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
WebCoreFloatToSkScalar(points[0].y()));
for (size_t i = 1; i < numPoints; ++i) {
path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
WebCoreFloatToSkScalar(points[i].y()));
}
/* The code used to just blindly call this
path->setIsConvex(true);
But webkit can sometimes send us non-convex 4-point values, so we mark the path's
convexity as unknown, so it will get computed by skia at draw time.
See crbug.com 108605
*/
SkPath::Convexity convexity = SkPath::kConvex_Convexity;
if (numPoints == 4)
convexity = SkPath::kUnknown_Convexity;
path->setConvexity(convexity);
}
| 170,976 |
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 ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
Commit Message: ipv4: Missing sk_nulls_node_init() in ping_unhash().
If we don't do that, then the poison value is left in the ->pprev
backlink.
This can cause crashes if we do a disconnect, followed by a connect().
Tested-by: Linus Torvalds <[email protected]>
Reported-by: Wen Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | void ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sk_nulls_node_init(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
| 166,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: SynchronousCompositorOutputSurface::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(HasClient());
DCHECK(context_provider_.get());
surface_size_ = surface_size;
InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority,
transform_for_tile_priority, true);
return frame_holder_.Pass();
}
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 | SynchronousCompositorOutputSurface::DemandDrawHw(
const gfx::Size& surface_size,
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) {
DCHECK(CalledOnValidThread());
DCHECK(HasClient());
DCHECK(context_provider_.get());
surface_size_ = surface_size;
InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority,
transform_for_tile_priority, true);
return frame_holder_.Pass();
}
| 171,621 |
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: const SegmentInfo* Segment::GetInfo() const
{
return m_pInfo;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const SegmentInfo* Segment::GetInfo() const
Chapters::~Chapters() {
while (m_editions_count > 0) {
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
}
| 174,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 AudioOutputDevice::Stop() {
{
base::AutoLock auto_lock(audio_thread_lock_);
audio_thread_->Stop(MessageLoop::current());
audio_thread_.reset();
}
message_loop()->PostTask(FROM_HERE,
base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this));
}
Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call.
I've kept my unit test changes intact but disabled until I get a proper fix.
BUG=147499,150805
TBR=henrika
Review URL: https://codereview.chromium.org/10946040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void AudioOutputDevice::Stop() {
{
base::AutoLock auto_lock(audio_thread_lock_);
audio_thread_.Stop(MessageLoop::current());
}
message_loop()->PostTask(FROM_HERE,
base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this));
}
| 170,707 |
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 DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels,
int width,
int height,
ReadbackOrder readback_order,
WebGLImageConversion::AlphaOp op) {
DCHECK(state_restorer_);
state_restorer_->SetPixelPackAlignmentDirty();
gl_->PixelStorei(GL_PACK_ALIGNMENT, 1);
gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
size_t buffer_size = 4 * width * height;
if (readback_order == kReadbackSkia) {
#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
for (size_t i = 0; i < buffer_size; i += 4) {
std::swap(pixels[i], pixels[i + 2]);
}
#endif
}
if (op == WebGLImageConversion::kAlphaDoPremultiply) {
for (size_t i = 0; i < buffer_size; i += 4) {
pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
}
} else if (op != WebGLImageConversion::kAlphaDoNothing) {
NOTREACHED();
}
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119 | void DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels,
int width,
int height,
ReadbackOrder readback_order,
WebGLImageConversion::AlphaOp op) {
DCHECK(state_restorer_);
state_restorer_->SetPixelPackParametersDirty();
gl_->PixelStorei(GL_PACK_ALIGNMENT, 1);
if (webgl_version_ > kWebGL1) {
gl_->PixelStorei(GL_PACK_SKIP_ROWS, 0);
gl_->PixelStorei(GL_PACK_SKIP_PIXELS, 0);
gl_->PixelStorei(GL_PACK_ROW_LENGTH, 0);
state_restorer_->SetPixelPackBufferBindingDirty();
gl_->BindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}
gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
size_t buffer_size = 4 * width * height;
if (readback_order == kReadbackSkia) {
#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
for (size_t i = 0; i < buffer_size; i += 4) {
std::swap(pixels[i], pixels[i + 2]);
}
#endif
}
if (op == WebGLImageConversion::kAlphaDoPremultiply) {
for (size_t i = 0; i < buffer_size; i += 4) {
pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
}
} else if (op != WebGLImageConversion::kAlphaDoNothing) {
NOTREACHED();
}
}
| 172,294 |
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: PP_Flash_Menu* ReadMenu(int depth,
const IPC::Message* m,
PickleIterator* iter) {
if (depth > kMaxMenuDepth)
return NULL;
++depth;
PP_Flash_Menu* menu = new PP_Flash_Menu;
menu->items = NULL;
if (!m->ReadUInt32(iter, &menu->count)) {
FreeMenu(menu);
return NULL;
}
if (menu->count == 0)
return menu;
menu->items = new PP_Flash_MenuItem[menu->count];
memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count);
for (uint32_t i = 0; i < menu->count; ++i) {
if (!ReadMenuItem(depth, m, iter, menu->items + i)) {
FreeMenu(menu);
return NULL;
}
}
return menu;
}
Commit Message: IPC: defend against excessive number of submenu entries in PPAPI message.
BUG=168710
Review URL: https://codereview.chromium.org/11794037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175576 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | PP_Flash_Menu* ReadMenu(int depth,
const IPC::Message* m,
PickleIterator* iter) {
if (depth > kMaxMenuDepth)
return NULL;
++depth;
PP_Flash_Menu* menu = new PP_Flash_Menu;
menu->items = NULL;
if (!m->ReadUInt32(iter, &menu->count)) {
FreeMenu(menu);
return NULL;
}
if (menu->count == 0)
return menu;
if (menu->count > kMaxMenuEntries) {
FreeMenu(menu);
return NULL;
}
menu->items = new PP_Flash_MenuItem[menu->count];
memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count);
for (uint32_t i = 0; i < menu->count; ++i) {
if (!ReadMenuItem(depth, m, iter, menu->items + i)) {
FreeMenu(menu);
return NULL;
}
}
return menu;
}
| 171,401 |
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 aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata;
return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg);
}
Commit Message: aacraid: missing capable() check in compat ioctl
In commit d496f94d22d1 ('[SCSI] aacraid: fix security weakness') we
added a check on CAP_SYS_RAWIO to the ioctl. The compat ioctls need the
check as well.
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg);
}
| 165,939 |
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 BluetoothDeviceChromeOS::ExpectingPinCode() const {
return !pincode_callback_.is_null();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool BluetoothDeviceChromeOS::ExpectingPinCode() const {
return pairing_context_.get() && pairing_context_->ExpectingPinCode();
}
| 171,226 |
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_set_PLTE(png_structp png_ptr, png_infop info_ptr,
png_colorp palette, int num_palette)
{
png_debug1(1, "in %s storage function", "PLTE");
if (png_ptr == NULL || info_ptr == NULL)
return;
if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
{
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
png_error(png_ptr, "Invalid palette length");
else
{
png_warning(png_ptr, "Invalid palette length");
return;
}
}
/* It may not actually be necessary to set png_ptr->palette here;
* we do it for backward compatibility with the way the png_handle_tRNS
* function used to do the allocation.
*/
#ifdef PNG_FREE_ME_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
#endif
/* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
* of num_palette entries, in case of an invalid PNG file that has
* too-large sample values.
*/
png_ptr->palette = (png_colorp)png_calloc(png_ptr,
PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color));
info_ptr->palette = png_ptr->palette;
info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_PLTE;
#else
png_ptr->flags |= PNG_FLAG_FREE_PLTE;
#endif
info_ptr->valid |= PNG_INFO_PLTE;
}
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_set_PLTE(png_structp png_ptr, png_infop info_ptr,
png_colorp palette, int num_palette)
{
png_uint_32 max_palette_length;
png_debug1(1, "in %s storage function", "PLTE");
if (png_ptr == NULL || info_ptr == NULL)
return;
max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
(1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
if (num_palette < 0 || num_palette > (int) max_palette_length)
{
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
png_error(png_ptr, "Invalid palette length");
else
{
png_warning(png_ptr, "Invalid palette length");
return;
}
}
/* It may not actually be necessary to set png_ptr->palette here;
* we do it for backward compatibility with the way the png_handle_tRNS
* function used to do the allocation.
*/
#ifdef PNG_FREE_ME_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
#endif
/* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
* of num_palette entries, in case of an invalid PNG file or incorrect
* call to png_set_PLTE() with too-large sample values.
*/
png_ptr->palette = (png_colorp)png_calloc(png_ptr,
PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color));
info_ptr->palette = png_ptr->palette;
info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_PLTE;
#else
png_ptr->flags |= PNG_FLAG_FREE_PLTE;
#endif
info_ptr->valid |= PNG_INFO_PLTE;
}
| 172,183 |
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_png_set_rgb_to_gray_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
PNG_CONST int error_action = 1; /* no error, no defines in png.h */
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
# else
png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
data.green_to_set);
# endif
# ifdef PNG_READ_cHRM_SUPPORTED
if (that->pm->current_encoding != 0)
{
/* We have an encoding so a cHRM chunk may have been set; if so then
* check that the libpng APIs give the correct (X,Y,Z) values within
* some margin of error for the round trip through the chromaticity
* form.
*/
# ifdef PNG_FLOATING_POINT_SUPPORTED
# define API_function png_get_cHRM_XYZ
# define API_form "FP"
# define API_type double
# define API_cvt(x) (x)
# else
# define API_function png_get_cHRM_XYZ_fixed
# define API_form "fixed"
# define API_type png_fixed_point
# define API_cvt(x) ((double)(x)/PNG_FP_1)
# endif
API_type rX, gX, bX;
API_type rY, gY, bY;
API_type rZ, gZ, bZ;
if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
& PNG_INFO_cHRM) != 0)
{
double maxe;
PNG_CONST char *el;
color_encoding e, o;
/* Expect libpng to return a normalized result, but the original
* color space encoding may not be normalized.
*/
modifier_current_encoding(that->pm, &o);
normalize_color_encoding(&o);
/* Sanity check the pngvalid code - the coefficients should match
* the normalized Y values of the encoding unless they were
* overridden.
*/
if (data.red_to_set == -1 && data.green_to_set == -1 &&
(fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
png_error(pp, "internal pngvalid cHRM coefficient error");
/* Generate a colour space encoding. */
e.gamma = o.gamma; /* not used */
e.red.X = API_cvt(rX);
e.red.Y = API_cvt(rY);
e.red.Z = API_cvt(rZ);
e.green.X = API_cvt(gX);
e.green.Y = API_cvt(gY);
e.green.Z = API_cvt(gZ);
e.blue.X = API_cvt(bX);
e.blue.Y = API_cvt(bY);
e.blue.Z = API_cvt(bZ);
/* This should match the original one from the png_modifier, within
* the range permitted by the libpng fixed point representation.
*/
maxe = 0;
el = "-"; /* Set to element name with error */
# define CHECK(col,x)\
{\
double err = fabs(o.col.x - e.col.x);\
if (err > maxe)\
{\
maxe = err;\
el = #col "(" #x ")";\
}\
}
CHECK(red,X)
CHECK(red,Y)
CHECK(red,Z)
CHECK(green,X)
CHECK(green,Y)
CHECK(green,Z)
CHECK(blue,X)
CHECK(blue,Y)
CHECK(blue,Z)
/* Here in both fixed and floating cases to check the values read
* from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
* we can't expect better than +/-.5E-5 on the result, allow 1E-5.
*/
if (maxe >= 1E-5)
{
size_t pos = 0;
char buffer[256];
pos = safecat(buffer, sizeof buffer, pos, API_form);
pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
pos = safecat(buffer, sizeof buffer, pos, el);
pos = safecat(buffer, sizeof buffer, pos, " error: ");
pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
pos = safecat(buffer, sizeof buffer, pos, " ");
/* Print the color space without the gamma value: */
pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
pos = safecat(buffer, sizeof buffer, pos, " -> ");
pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
png_error(pp, buffer);
}
}
}
# endif /* READ_cHRM */
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_rgb_to_gray_set(PNG_CONST image_transform *this,
image_transform_png_set_rgb_to_gray_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
const int error_action = 1; /* no error, no defines in png.h */
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
# else
png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
data.green_to_set);
# endif
# ifdef PNG_READ_cHRM_SUPPORTED
if (that->pm->current_encoding != 0)
{
/* We have an encoding so a cHRM chunk may have been set; if so then
* check that the libpng APIs give the correct (X,Y,Z) values within
* some margin of error for the round trip through the chromaticity
* form.
*/
# ifdef PNG_FLOATING_POINT_SUPPORTED
# define API_function png_get_cHRM_XYZ
# define API_form "FP"
# define API_type double
# define API_cvt(x) (x)
# else
# define API_function png_get_cHRM_XYZ_fixed
# define API_form "fixed"
# define API_type png_fixed_point
# define API_cvt(x) ((double)(x)/PNG_FP_1)
# endif
API_type rX, gX, bX;
API_type rY, gY, bY;
API_type rZ, gZ, bZ;
if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
& PNG_INFO_cHRM) != 0)
{
double maxe;
const char *el;
color_encoding e, o;
/* Expect libpng to return a normalized result, but the original
* color space encoding may not be normalized.
*/
modifier_current_encoding(that->pm, &o);
normalize_color_encoding(&o);
/* Sanity check the pngvalid code - the coefficients should match
* the normalized Y values of the encoding unless they were
* overridden.
*/
if (data.red_to_set == -1 && data.green_to_set == -1 &&
(fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
png_error(pp, "internal pngvalid cHRM coefficient error");
/* Generate a colour space encoding. */
e.gamma = o.gamma; /* not used */
e.red.X = API_cvt(rX);
e.red.Y = API_cvt(rY);
e.red.Z = API_cvt(rZ);
e.green.X = API_cvt(gX);
e.green.Y = API_cvt(gY);
e.green.Z = API_cvt(gZ);
e.blue.X = API_cvt(bX);
e.blue.Y = API_cvt(bY);
e.blue.Z = API_cvt(bZ);
/* This should match the original one from the png_modifier, within
* the range permitted by the libpng fixed point representation.
*/
maxe = 0;
el = "-"; /* Set to element name with error */
# define CHECK(col,x)\
{\
double err = fabs(o.col.x - e.col.x);\
if (err > maxe)\
{\
maxe = err;\
el = #col "(" #x ")";\
}\
}
CHECK(red,X)
CHECK(red,Y)
CHECK(red,Z)
CHECK(green,X)
CHECK(green,Y)
CHECK(green,Z)
CHECK(blue,X)
CHECK(blue,Y)
CHECK(blue,Z)
/* Here in both fixed and floating cases to check the values read
* from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
* we can't expect better than +/-.5E-5 on the result, allow 1E-5.
*/
if (maxe >= 1E-5)
{
size_t pos = 0;
char buffer[256];
pos = safecat(buffer, sizeof buffer, pos, API_form);
pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
pos = safecat(buffer, sizeof buffer, pos, el);
pos = safecat(buffer, sizeof buffer, pos, " error: ");
pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
pos = safecat(buffer, sizeof buffer, pos, " ");
/* Print the color space without the gamma value: */
pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
pos = safecat(buffer, sizeof buffer, pos, " -> ");
pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
png_error(pp, buffer);
}
}
}
# endif /* READ_cHRM */
this->next->set(this->next, that, pp, pi);
}
| 173,644 |
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 Document::SetFocusedElement(Element* new_focused_element,
const FocusParams& params) {
DCHECK(!lifecycle_.InDetach());
clear_focused_element_timer_.Stop();
if (new_focused_element && (new_focused_element->GetDocument() != this))
return true;
if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element))
return true;
if (focused_element_ == new_focused_element)
return true;
bool focus_change_blocked = false;
Element* old_focused_element = focused_element_;
focused_element_ = nullptr;
UpdateDistributionForFlatTreeTraversal();
Node* ancestor = (old_focused_element && old_focused_element->isConnected() &&
new_focused_element)
? FlatTreeTraversal::CommonAncestor(*old_focused_element,
*new_focused_element)
: nullptr;
if (old_focused_element) {
old_focused_element->SetFocused(false, params.type);
old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
old_focused_element->DispatchBlurEvent(new_focused_element, params.type,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
old_focused_element->DispatchFocusOutEvent(event_type_names::kFocusout,
new_focused_element,
params.source_capabilities);
old_focused_element->DispatchFocusOutEvent(event_type_names::kDOMFocusOut,
new_focused_element,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
}
}
if (new_focused_element)
UpdateStyleAndLayoutTreeForNode(new_focused_element);
if (new_focused_element && new_focused_element->IsFocusable()) {
if (IsRootEditableElement(*new_focused_element) &&
!AcceptsEditingFocus(*new_focused_element)) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_ = new_focused_element;
SetSequentialFocusNavigationStartingPoint(focused_element_.Get());
if (params.type != kWebFocusTypeNone)
last_focus_type_ = params.type;
focused_element_->SetFocused(true, params.type);
focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
CancelFocusAppearanceUpdate();
EnsurePaintLocationDataValidForNode(focused_element_);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_->UpdateFocusAppearanceWithOptions(
params.selection_behavior, params.options);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
focused_element_->DispatchFocusEvent(old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_->DispatchFocusInEvent(event_type_names::kFocusin,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_->DispatchFocusInEvent(event_type_names::kDOMFocusIn,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
}
}
if (!focus_change_blocked && focused_element_) {
if (AXObjectCache* cache = ExistingAXObjectCache()) {
cache->HandleFocusedUIElementChanged(old_focused_element,
new_focused_element);
}
}
if (!focus_change_blocked && GetPage()) {
GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element,
focused_element_.Get());
}
SetFocusedElementDone:
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return !focus_change_blocked;
}
Commit Message: Cleanup and remove dead code in SetFocusedElement
This early-out was added in:
https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc
Back then, we applied fragment focus in LayoutUpdated() which could
cause this issue. This got cleaned up in:
https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2
so that focus is no longer applied after layout.
+Cleanup: Goto considered harmful
Bug: 795381
Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417
Commit-Queue: David Bokan <[email protected]>
Reviewed-by: Stefan Zager <[email protected]>
Cr-Commit-Position: refs/heads/master@{#641101}
CWE ID: CWE-416 | bool Document::SetFocusedElement(Element* new_focused_element,
const FocusParams& params) {
DCHECK(!lifecycle_.InDetach());
clear_focused_element_timer_.Stop();
if (new_focused_element && (new_focused_element->GetDocument() != this))
return true;
if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element))
return true;
if (focused_element_ == new_focused_element)
return true;
bool focus_change_blocked = false;
Element* old_focused_element = focused_element_;
focused_element_ = nullptr;
UpdateDistributionForFlatTreeTraversal();
Node* ancestor = (old_focused_element && old_focused_element->isConnected() &&
new_focused_element)
? FlatTreeTraversal::CommonAncestor(*old_focused_element,
*new_focused_element)
: nullptr;
if (old_focused_element) {
old_focused_element->SetFocused(false, params.type);
old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
old_focused_element->DispatchBlurEvent(new_focused_element, params.type,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
old_focused_element->DispatchFocusOutEvent(event_type_names::kFocusout,
new_focused_element,
params.source_capabilities);
old_focused_element->DispatchFocusOutEvent(event_type_names::kDOMFocusOut,
new_focused_element,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
}
}
if (new_focused_element)
UpdateStyleAndLayoutTreeForNode(new_focused_element);
if (new_focused_element && new_focused_element->IsFocusable()) {
if (IsRootEditableElement(*new_focused_element) &&
!AcceptsEditingFocus(*new_focused_element)) {
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return false;
}
focused_element_ = new_focused_element;
SetSequentialFocusNavigationStartingPoint(focused_element_.Get());
if (params.type != kWebFocusTypeNone)
last_focus_type_ = params.type;
focused_element_->SetFocused(true, params.type);
focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor);
if (focused_element_ != new_focused_element) {
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return false;
}
CancelFocusAppearanceUpdate();
EnsurePaintLocationDataValidForNode(focused_element_);
focused_element_->UpdateFocusAppearanceWithOptions(
params.selection_behavior, params.options);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
focused_element_->DispatchFocusEvent(old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return false;
}
focused_element_->DispatchFocusInEvent(event_type_names::kFocusin,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return false;
}
focused_element_->DispatchFocusInEvent(event_type_names::kDOMFocusIn,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return false;
}
}
}
if (!focus_change_blocked && focused_element_) {
if (AXObjectCache* cache = ExistingAXObjectCache()) {
cache->HandleFocusedUIElementChanged(old_focused_element,
new_focused_element);
}
}
if (!focus_change_blocked && GetPage()) {
GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element,
focused_element_.Get());
}
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return !focus_change_blocked;
}
| 172,046 |
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: TabGroupHeader::TabGroupHeader(const base::string16& group_title) {
constexpr gfx::Insets kPlaceholderInsets = gfx::Insets(4, 27);
SetBorder(views::CreateEmptyBorder(kPlaceholderInsets));
views::FlexLayout* layout =
SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetCollapseMargins(true)
.SetMainAxisAlignment(views::LayoutAlignment::kStart)
.SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
auto title = std::make_unique<views::Label>(group_title);
title->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD);
title->SetElideBehavior(gfx::FADE_TAIL);
auto* title_ptr = AddChildView(std::move(title));
layout->SetFlexForView(title_ptr,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kScaleToZero,
views::MaximumFlexSizeRule::kUnbounded));
auto group_menu_button = views::CreateVectorImageButton(/*listener*/ nullptr);
views::SetImageFromVectorIcon(group_menu_button.get(), kBrowserToolsIcon);
AddChildView(std::move(group_menu_button));
}
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 | TabGroupHeader::TabGroupHeader(const base::string16& group_title) {
TabGroupHeader::TabGroupHeader(TabController* controller, int group)
: controller_(controller), group_(group) {
DCHECK(controller);
constexpr gfx::Insets kPlaceholderInsets = gfx::Insets(4, 27);
SetBorder(views::CreateEmptyBorder(kPlaceholderInsets));
views::FlexLayout* layout =
SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetCollapseMargins(true)
.SetMainAxisAlignment(views::LayoutAlignment::kStart)
.SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
auto title = std::make_unique<views::Label>(GetGroupData()->title());
title->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD);
title->SetElideBehavior(gfx::FADE_TAIL);
title_label_ = AddChildView(std::move(title));
layout->SetFlexForView(title_label_,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kScaleToZero,
views::MaximumFlexSizeRule::kUnbounded));
auto group_menu_button = views::CreateVectorImageButton(/*listener*/ nullptr);
views::SetImageFromVectorIcon(group_menu_button.get(), kBrowserToolsIcon);
AddChildView(std::move(group_menu_button));
}
| 172,519 |
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 ExtensionTtsPlatformImplWin::Speak(
const std::string& src_utterance,
const std::string& language,
const std::string& gender,
double rate,
double pitch,
double volume) {
std::wstring utterance = UTF8ToUTF16(src_utterance);
if (!speech_synthesizer_)
return false;
if (rate >= 0.0) {
speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10));
}
if (pitch >= 0.0) {
std::wstring pitch_value =
base::IntToString16(static_cast<int>(pitch * 20 - 10));
utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" +
utterance + L"</pitch>";
}
if (volume >= 0.0) {
speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100));
}
if (paused_) {
speech_synthesizer_->Resume();
paused_ = false;
}
speech_synthesizer_->Speak(
utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ExtensionTtsPlatformImplWin::Speak(
int utterance_id,
const std::string& src_utterance,
const std::string& lang,
const UtteranceContinuousParameters& params) {
std::wstring prefix;
std::wstring suffix;
if (!speech_synthesizer_)
return false;
// TODO(dmazzoni): support languages other than the default: crbug.com/88059
if (params.rate >= 0.0) {
// Map our multiplicative range of 0.1x to 10.0x onto Microsoft's
// linear range of -10 to 10:
// 0.1 -> -10
// 1.0 -> 0
// 10.0 -> 10
speech_synthesizer_->SetRate(static_cast<int32>(10 * log10(params.rate)));
}
if (params.pitch >= 0.0) {
std::wstring pitch_value =
base::IntToString16(static_cast<int>(params.pitch * 10 - 10));
prefix = L"<pitch absmiddle=\"" + pitch_value + L"\">";
suffix = L"</pitch>";
}
if (params.volume >= 0.0) {
speech_synthesizer_->SetVolume(static_cast<uint16>(params.volume * 100));
}
if (paused_) {
speech_synthesizer_->Resume();
paused_ = false;
}
// TODO(dmazzoni): convert SSML to SAPI xml. http://crbug.com/88072
utterance_ = UTF8ToWide(src_utterance);
utterance_id_ = utterance_id;
char_position_ = 0;
std::wstring merged_utterance = prefix + utterance_ + suffix;
prefix_len_ = prefix.size();
HRESULT result = speech_synthesizer_->Speak(
merged_utterance.c_str(),
SPF_ASYNC | SPF_PURGEBEFORESPEAK,
&stream_number_);
return (result == S_OK);
}
| 170,402 |
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 FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
WebFrameLoadType frame_load_type,
NavigationPolicy policy) {
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(passed_request.TriggeringEventInfo() !=
WebTriggeringEventInfo::kUnknown);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
element->CancelPendingLazyLoad();
if (in_stop_all_loaders_)
return;
FrameLoadRequest request(passed_request);
ResourceRequest& resource_request = request.GetResourceRequest();
const KURL& url = resource_request.Url();
Document* origin_document = request.OriginDocument();
resource_request.SetHasUserGesture(
LocalFrame::HasTransientUserActivation(frame_));
if (!PrepareRequestForThisFrame(request))
return;
Frame* target_frame =
request.Form() ? nullptr
: frame_->FindFrameForNavigation(
AtomicString(request.FrameName()), *frame_, url);
bool should_navigate_target_frame = policy == kNavigationPolicyCurrentTab;
if (target_frame && target_frame != frame_ && should_navigate_target_frame) {
if (target_frame->IsLocalFrame() &&
!ToLocalFrame(target_frame)->IsNavigationAllowed()) {
return;
}
bool was_in_same_page = target_frame->GetPage() == frame_->GetPage();
request.SetFrameName("_self");
target_frame->Navigate(request, frame_load_type);
Page* page = target_frame->GetPage();
if (!was_in_same_page && page)
page->GetChromeClient().Focus(frame_);
return;
}
SetReferrerForFrameRequest(request);
if (!target_frame && !request.FrameName().IsEmpty()) {
if (policy == kNavigationPolicyDownload) {
Client()->DownloadURL(resource_request,
DownloadCrossOriginRedirects::kFollow);
return; // Navigation/download will be handled by the client.
} else if (should_navigate_target_frame) {
resource_request.SetFrameType(
network::mojom::RequestContextFrameType::kAuxiliary);
CreateWindowForRequest(request, *frame_);
return; // Navigation will be handled by the new frame/window.
}
}
if (!frame_->IsNavigationAllowed() ||
frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal) {
return;
}
frame_load_type = DetermineFrameLoadType(resource_request, origin_document,
KURL(), frame_load_type);
bool same_document_navigation =
policy == kNavigationPolicyCurrentTab &&
ShouldPerformFragmentNavigation(
request.Form(), resource_request.HttpMethod(), frame_load_type, url);
if (same_document_navigation) {
CommitSameDocumentNavigation(
url, frame_load_type, nullptr, request.ClientRedirect(),
origin_document,
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent,
nullptr /* extra_data */);
return;
}
WebNavigationType navigation_type = DetermineNavigationType(
frame_load_type, resource_request.HttpBody() || request.Form(),
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent);
resource_request.SetRequestContext(
DetermineRequestContextFromNavigationType(navigation_type));
resource_request.SetFrameType(
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
mojom::blink::NavigationInitiatorPtr navigation_initiator;
if (origin_document && origin_document->GetContentSecurityPolicy()
->ExperimentalFeaturesEnabled()) {
WebContentSecurityPolicyList initiator_csp =
origin_document->GetContentSecurityPolicy()
->ExposeForNavigationalChecks();
resource_request.SetInitiatorCSP(initiator_csp);
auto request = mojo::MakeRequest(&navigation_initiator);
origin_document->BindNavigationInitiatorRequest(std::move(request));
}
RecordLatestRequiredCSP();
ModifyRequestForCSP(resource_request, origin_document);
DCHECK(Client()->HasWebView());
if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) {
Deprecation::CountDeprecation(
frame_, WebFeature::kCanRequestURLHTTPContainingNewline);
return;
}
bool has_transient_activation =
LocalFrame::HasTransientUserActivation(frame_);
if (frame_->IsMainFrame() && origin_document &&
frame_->GetPage() == origin_document->GetPage()) {
LocalFrame::ConsumeTransientUserActivation(frame_);
}
Client()->BeginNavigation(
resource_request, origin_document, nullptr /* document_loader */,
navigation_type, policy, has_transient_activation, frame_load_type,
request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect,
request.TriggeringEventInfo(), request.Form(),
request.ShouldCheckMainWorldContentSecurityPolicy(),
request.GetBlobURLToken(), request.GetInputStartTime(),
request.HrefTranslate().GetString(), std::move(navigation_initiator));
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20 | void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
WebFrameLoadType frame_load_type,
NavigationPolicy policy) {
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(passed_request.TriggeringEventInfo() !=
WebTriggeringEventInfo::kUnknown);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
element->CancelPendingLazyLoad();
if (in_stop_all_loaders_)
return;
FrameLoadRequest request(passed_request);
ResourceRequest& resource_request = request.GetResourceRequest();
const KURL& url = resource_request.Url();
Document* origin_document = request.OriginDocument();
resource_request.SetHasUserGesture(
LocalFrame::HasTransientUserActivation(frame_));
if (!PrepareRequestForThisFrame(request))
return;
Frame* target_frame =
request.Form() ? nullptr
: frame_->FindFrameForNavigation(
AtomicString(request.FrameName()), *frame_, url);
bool should_navigate_target_frame = policy == kNavigationPolicyCurrentTab;
if (target_frame && target_frame != frame_ && should_navigate_target_frame) {
if (target_frame->IsLocalFrame() &&
!ToLocalFrame(target_frame)->IsNavigationAllowed()) {
return;
}
bool was_in_same_page = target_frame->GetPage() == frame_->GetPage();
request.SetFrameName("_self");
target_frame->Navigate(request, frame_load_type);
Page* page = target_frame->GetPage();
if (!was_in_same_page && page)
page->GetChromeClient().Focus(frame_);
return;
}
SetReferrerForFrameRequest(request);
if (!target_frame && !request.FrameName().IsEmpty()) {
if (policy == kNavigationPolicyDownload) {
Client()->DownloadURL(resource_request,
DownloadCrossOriginRedirects::kFollow);
return; // Navigation/download will be handled by the client.
} else if (should_navigate_target_frame) {
resource_request.SetFrameType(
network::mojom::RequestContextFrameType::kAuxiliary);
CreateWindowForRequest(request, *frame_);
return; // Navigation will be handled by the new frame/window.
}
}
if (!frame_->IsNavigationAllowed() ||
frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal) {
return;
}
frame_load_type = DetermineFrameLoadType(resource_request, origin_document,
KURL(), frame_load_type);
bool same_document_navigation =
policy == kNavigationPolicyCurrentTab &&
ShouldPerformFragmentNavigation(
request.Form(), resource_request.HttpMethod(), frame_load_type, url);
if (same_document_navigation) {
CommitSameDocumentNavigation(
url, frame_load_type, nullptr, request.ClientRedirect(),
origin_document,
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent,
nullptr /* extra_data */);
return;
}
WebNavigationType navigation_type = DetermineNavigationType(
frame_load_type, resource_request.HttpBody() || request.Form(),
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent);
resource_request.SetRequestContext(
DetermineRequestContextFromNavigationType(navigation_type));
resource_request.SetFrameType(
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
mojom::blink::NavigationInitiatorPtr navigation_initiator;
if (origin_document && origin_document->GetContentSecurityPolicy()
->ExperimentalFeaturesEnabled()) {
WebContentSecurityPolicyList initiator_csp =
origin_document->GetContentSecurityPolicy()
->ExposeForNavigationalChecks();
resource_request.SetInitiatorCSP(initiator_csp);
auto request = mojo::MakeRequest(&navigation_initiator);
origin_document->BindNavigationInitiatorRequest(std::move(request));
}
last_origin_document_ = origin_document;
RecordLatestRequiredCSP();
ModifyRequestForCSP(resource_request, origin_document);
DCHECK(Client()->HasWebView());
if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) {
Deprecation::CountDeprecation(
frame_, WebFeature::kCanRequestURLHTTPContainingNewline);
return;
}
bool has_transient_activation =
LocalFrame::HasTransientUserActivation(frame_);
if (frame_->IsMainFrame() && origin_document &&
frame_->GetPage() == origin_document->GetPage()) {
LocalFrame::ConsumeTransientUserActivation(frame_);
}
Client()->BeginNavigation(
resource_request, origin_document, nullptr /* document_loader */,
navigation_type, policy, has_transient_activation, frame_load_type,
request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect,
request.TriggeringEventInfo(), request.Form(),
request.ShouldCheckMainWorldContentSecurityPolicy(),
request.GetBlobURLToken(), request.GetInputStartTime(),
request.HrefTranslate().GetString(), std::move(navigation_initiator));
}
| 173,058 |
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: GLSurfaceEGLSurfaceControl::GLSurfaceEGLSurfaceControl(
ANativeWindow* window,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: root_surface_(new SurfaceControl::Surface(window, kRootSurfaceName)),
gpu_task_runner_(std::move(task_runner)),
weak_factory_(this) {}
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: | GLSurfaceEGLSurfaceControl::GLSurfaceEGLSurfaceControl(
ANativeWindow* window,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: window_rect_(0,
0,
ANativeWindow_getWidth(window),
ANativeWindow_getHeight(window)),
root_surface_(new SurfaceControl::Surface(window, kRootSurfaceName)),
gpu_task_runner_(std::move(task_runner)),
weak_factory_(this) {}
| 172,109 |
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 WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
RuntimeEnabledFeatures::SetRequireCSSExtensionForFileEnabled(enable);
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254 | void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
| 173,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: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609
CWE ID: CWE-125 | MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if ((width == 0) || (height == 0))
return(threshold_image);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
| 170,206 |
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: struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
struct inet_peer *inet_getpeer(const struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count,
(daddr->family == AF_INET) ?
secure_ip_id(daddr->addr.a4) :
secure_ipv6_id(daddr->addr.a6));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
| 165,850 |
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: X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
X509_REQ *ret;
X509_REQ_INFO *ri;
int i;
EVP_PKEY *pktmp;
ret = X509_REQ_new();
if (ret == NULL) {
X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE);
goto err;
}
ri = ret->req_info;
ri->version->length = 1;
ri->version->data = (unsigned char *)OPENSSL_malloc(1);
if (ri->version->data == NULL)
goto err;
ri->version->data[0] = 0; /* version == 0 */
if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x)))
goto err;
pktmp = X509_get_pubkey(x);
i = X509_REQ_set_pubkey(ret, pktmp);
EVP_PKEY_free(pktmp);
if (!i)
if (pkey != NULL) {
if (!X509_REQ_sign(ret, pkey, md))
goto err;
}
return (ret);
err:
X509_REQ_free(ret);
return (NULL);
}
Commit Message:
CWE ID: | X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
X509_REQ *ret;
X509_REQ_INFO *ri;
int i;
EVP_PKEY *pktmp;
ret = X509_REQ_new();
if (ret == NULL) {
X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE);
goto err;
}
ri = ret->req_info;
ri->version->length = 1;
ri->version->data = (unsigned char *)OPENSSL_malloc(1);
if (ri->version->data == NULL)
goto err;
ri->version->data[0] = 0; /* version == 0 */
if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x)))
goto err;
pktmp = X509_get_pubkey(x);
if (pktmp == NULL)
goto err;
i = X509_REQ_set_pubkey(ret, pktmp);
EVP_PKEY_free(pktmp);
if (!i)
if (pkey != NULL) {
if (!X509_REQ_sign(ret, pkey, md))
goto err;
}
return (ret);
err:
X509_REQ_free(ret);
return (NULL);
}
| 164,809 |
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 DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#574437}
CWE ID: | void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) {
if (!initial_page_host_.empty())
restricted_hosts_.emplace(initial_page_host_);
}
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
| 173,190 |
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 faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
unsigned long address, unsigned int *flags, int *nonblocking)
{
unsigned int fault_flags = 0;
int ret;
/* mlock all present pages, but do not fault in new pages */
if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
return -ENOENT;
/* For mm_populate(), just skip the stack guard page. */
if ((*flags & FOLL_POPULATE) &&
(stack_guard_page_start(vma, address) ||
stack_guard_page_end(vma, address + PAGE_SIZE)))
return -ENOENT;
if (*flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (*flags & FOLL_REMOTE)
fault_flags |= FAULT_FLAG_REMOTE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (*flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
if (*flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = handle_mm_fault(vma, address, fault_flags);
if (ret & VM_FAULT_ERROR) {
if (ret & VM_FAULT_OOM)
return -ENOMEM;
if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT;
if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
return -EFAULT;
BUG();
}
if (tsk) {
if (ret & VM_FAULT_MAJOR)
tsk->maj_flt++;
else
tsk->min_flt++;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking)
*nonblocking = 0;
return -EBUSY;
}
/*
* The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
* necessary, even if maybe_mkwrite decided not to set pte_write. We
* can thus safely do subsequent page lookups as if they were reads.
* But only do so when looping for pte_write is futile: in some cases
* userspace may also be wanting to write to the gotten user page,
* which a read fault here might prevent (a readonly page might get
* reCOWed by userspace write).
*/
if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
*flags &= ~FOLL_WRITE;
return 0;
}
Commit Message: mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
This is an ancient bug that was actually attempted to be fixed once
(badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
get_user_pages() race for write access") but that was then undone due to
problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").
In the meantime, the s390 situation has long been fixed, and we can now
fix it by checking the pte_dirty() bit properly (and do it better). The
s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
software dirty bits") which made it into v3.9. Earlier kernels will
have to look at the page state itself.
Also, the VM has become more scalable, and what used a purely
theoretical race back then has become easier to trigger.
To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
we already did a COW" rather than play racy games with FOLL_WRITE that
is very fundamental, and then use the pte dirty flag to validate that
the FOLL_COW flag is still valid.
Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Reviewed-by: Michal Hocko <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Greg Thelen <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
unsigned long address, unsigned int *flags, int *nonblocking)
{
unsigned int fault_flags = 0;
int ret;
/* mlock all present pages, but do not fault in new pages */
if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
return -ENOENT;
/* For mm_populate(), just skip the stack guard page. */
if ((*flags & FOLL_POPULATE) &&
(stack_guard_page_start(vma, address) ||
stack_guard_page_end(vma, address + PAGE_SIZE)))
return -ENOENT;
if (*flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (*flags & FOLL_REMOTE)
fault_flags |= FAULT_FLAG_REMOTE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (*flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
if (*flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = handle_mm_fault(vma, address, fault_flags);
if (ret & VM_FAULT_ERROR) {
if (ret & VM_FAULT_OOM)
return -ENOMEM;
if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT;
if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
return -EFAULT;
BUG();
}
if (tsk) {
if (ret & VM_FAULT_MAJOR)
tsk->maj_flt++;
else
tsk->min_flt++;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking)
*nonblocking = 0;
return -EBUSY;
}
/*
* The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
* necessary, even if maybe_mkwrite decided not to set pte_write. We
* can thus safely do subsequent page lookups as if they were reads.
* But only do so when looping for pte_write is futile: in some cases
* userspace may also be wanting to write to the gotten user page,
* which a read fault here might prevent (a readonly page might get
* reCOWed by userspace write).
*/
if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
*flags |= FOLL_COW;
return 0;
}
| 167,163 |
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 set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
Commit Message:
CWE ID: CWE-264 | static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
switch (bits_per_pixel) {
case 8:
case 16:
case 32:
break;
default:
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
| 164,902 |
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: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int c, l;
xmlChar stop;
xmlChar *ret = NULL;
const xmlChar *cur = NULL;
xmlParserInputPtr input;
if (RAW == '"') stop = '"';
else if (RAW == '\'') stop = '\'';
else {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
/*
* The content of the entity definition is copied in a buffer.
*/
ctxt->instate = XML_PARSER_ENTITY_VALUE;
input = ctxt->input;
GROW;
NEXT;
c = CUR_CHAR(l);
/*
* NOTE: 4.4.5 Included in Literal
* When a parameter entity reference appears in a literal entity
* value, ... a single or double quote character in the replacement
* text is always treated as a normal data character and will not
* terminate the literal.
* In practice it means we stop the loop only when back at parsing
* the initial entity and the quote is found
*/
while ((IS_CHAR(c)) && ((c != stop) || /* checked */
(ctxt->input != input))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */
xmlPopInput(ctxt);
GROW;
c = CUR_CHAR(l);
if (c == 0) {
GROW;
c = CUR_CHAR(l);
}
}
buf[len] = 0;
/*
* Raise problem w.r.t. '&' and '%' being used in non-entities
* reference constructs. Note Charref will be handled in
* xmlStringDecodeEntities()
*/
cur = buf;
while (*cur != 0) { /* non input consuming */
if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) {
xmlChar *name;
xmlChar tmp = *cur;
cur++;
name = xmlParseStringName(ctxt, &cur);
if ((name == NULL) || (*cur != ';')) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
"EntityValue: '%c' forbidden except for entities references\n",
tmp);
}
if ((tmp == '%') && (ctxt->inSubset == 1) &&
(ctxt->inputNr == 1)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
}
if (name != NULL)
xmlFree(name);
if (*cur == 0)
break;
}
cur++;
}
/*
* Then PEReference entities are substituted.
*/
if (c != stop) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
xmlFree(buf);
} else {
NEXT;
/*
* NOTE: 4.4.7 Bypassed
* When a general entity reference appears in the EntityValue in
* an entity declaration, it is bypassed and left as is.
* so XML_SUBSTITUTE_REF is not set here.
*/
ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF,
0, 0, 0);
if (orig != NULL)
*orig = buf;
else
xmlFree(buf);
}
return(ret);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int c, l;
xmlChar stop;
xmlChar *ret = NULL;
const xmlChar *cur = NULL;
xmlParserInputPtr input;
if (RAW == '"') stop = '"';
else if (RAW == '\'') stop = '\'';
else {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
/*
* The content of the entity definition is copied in a buffer.
*/
ctxt->instate = XML_PARSER_ENTITY_VALUE;
input = ctxt->input;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
NEXT;
c = CUR_CHAR(l);
/*
* NOTE: 4.4.5 Included in Literal
* When a parameter entity reference appears in a literal entity
* value, ... a single or double quote character in the replacement
* text is always treated as a normal data character and will not
* terminate the literal.
* In practice it means we stop the loop only when back at parsing
* the initial entity and the quote is found
*/
while (((IS_CHAR(c)) && ((c != stop) || /* checked */
(ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */
xmlPopInput(ctxt);
GROW;
c = CUR_CHAR(l);
if (c == 0) {
GROW;
c = CUR_CHAR(l);
}
}
buf[len] = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
/*
* Raise problem w.r.t. '&' and '%' being used in non-entities
* reference constructs. Note Charref will be handled in
* xmlStringDecodeEntities()
*/
cur = buf;
while (*cur != 0) { /* non input consuming */
if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) {
xmlChar *name;
xmlChar tmp = *cur;
cur++;
name = xmlParseStringName(ctxt, &cur);
if ((name == NULL) || (*cur != ';')) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
"EntityValue: '%c' forbidden except for entities references\n",
tmp);
}
if ((tmp == '%') && (ctxt->inSubset == 1) &&
(ctxt->inputNr == 1)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
}
if (name != NULL)
xmlFree(name);
if (*cur == 0)
break;
}
cur++;
}
/*
* Then PEReference entities are substituted.
*/
if (c != stop) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
xmlFree(buf);
} else {
NEXT;
/*
* NOTE: 4.4.7 Bypassed
* When a general entity reference appears in the EntityValue in
* an entity declaration, it is bypassed and left as is.
* so XML_SUBSTITUTE_REF is not set here.
*/
ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF,
0, 0, 0);
if (orig != NULL)
*orig = buf;
else
xmlFree(buf);
}
return(ret);
}
| 171,290 |
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 uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) {
assert(data != NULL);
assert(length > 0);
if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) {
LOG_ERROR("%s invalid data type: %d", __func__, type);
return 0;
}
--data;
uint8_t previous_byte = *data;
*(data) = type;
++length;
uint16_t transmitted_length = 0;
while (length > 0) {
ssize_t ret = write(uart_fd, data + transmitted_length, length);
switch (ret) {
case -1:
LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno));
goto done;
case 0:
goto done;
default:
transmitted_length += ret;
length -= ret;
break;
}
}
done:;
*(data) = previous_byte;
if (transmitted_length > 0)
--transmitted_length;
return transmitted_length;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) {
assert(data != NULL);
assert(length > 0);
if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) {
LOG_ERROR("%s invalid data type: %d", __func__, type);
return 0;
}
--data;
uint8_t previous_byte = *data;
*(data) = type;
++length;
uint16_t transmitted_length = 0;
while (length > 0) {
ssize_t ret = TEMP_FAILURE_RETRY(write(uart_fd, data + transmitted_length, length));
switch (ret) {
case -1:
LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno));
goto done;
case 0:
goto done;
default:
transmitted_length += ret;
length -= ret;
break;
}
}
done:;
*(data) = previous_byte;
if (transmitted_length > 0)
--transmitted_length;
return transmitted_length;
}
| 173,476 |
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: pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
Commit Message:
CWE ID: CWE-189 | pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
/* sanity checks */
if ( firstCol < 0 ||
firstCol > lastCol ||
lastCol > 0xFF ||
firstRow < 0 ||
firstRow > lastRow ||
lastRow > 0xFF )
return FT_THROW( Invalid_Table );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
| 164,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: static void vnc_async_encoding_start(VncState *orig, VncState *local)
{
local->vnc_encoding = orig->vnc_encoding;
local->features = orig->features;
local->ds = orig->ds;
local->vd = orig->vd;
local->lossy_rect = orig->lossy_rect;
local->write_pixels = orig->write_pixels;
local->clientds = orig->clientds;
local->tight = orig->tight;
local->zlib = orig->zlib;
local->hextile = orig->hextile;
local->output = queue->buffer;
local->csock = -1; /* Don't do any network work on this thread */
buffer_reset(&local->output);
}
Commit Message:
CWE ID: CWE-125 | static void vnc_async_encoding_start(VncState *orig, VncState *local)
{
local->vnc_encoding = orig->vnc_encoding;
local->features = orig->features;
local->ds = orig->ds;
local->vd = orig->vd;
local->lossy_rect = orig->lossy_rect;
local->write_pixels = orig->write_pixels;
local->client_pf = orig->client_pf;
local->client_be = orig->client_be;
local->tight = orig->tight;
local->zlib = orig->zlib;
local->hextile = orig->hextile;
local->output = queue->buffer;
local->csock = -1; /* Don't do any network work on this thread */
buffer_reset(&local->output);
}
| 165,469 |
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 insn_get_code_seg_params(struct pt_regs *regs)
{
struct desc_struct *desc;
short sel;
if (v8086_mode(regs))
/* Address and operand size are both 16-bit. */
return INSN_CODE_SEG_PARAMS(2, 2);
sel = get_segment_selector(regs, INAT_SEG_REG_CS);
if (sel < 0)
return sel;
desc = get_desc(sel);
if (!desc)
return -EINVAL;
/*
* The most significant byte of the Type field of the segment descriptor
* determines whether a segment contains data or code. If this is a data
* segment, return error.
*/
if (!(desc->type & BIT(3)))
return -EINVAL;
switch ((desc->l << 1) | desc->d) {
case 0: /*
* Legacy mode. CS.L=0, CS.D=0. Address and operand size are
* both 16-bit.
*/
return INSN_CODE_SEG_PARAMS(2, 2);
case 1: /*
* Legacy mode. CS.L=0, CS.D=1. Address and operand size are
* both 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 4);
case 2: /*
* IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit;
* operand size is 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 8);
case 3: /* Invalid setting. CS.L=1, CS.D=1 */
/* fall through */
default:
return -EINVAL;
}
}
Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry
get_desc() computes a pointer into the LDT while holding a lock that
protects the LDT from being freed, but then drops the lock and returns the
(now potentially dangling) pointer to its caller.
Fix it by giving the caller a copy of the LDT entry instead.
Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | int insn_get_code_seg_params(struct pt_regs *regs)
{
struct desc_struct desc;
short sel;
if (v8086_mode(regs))
/* Address and operand size are both 16-bit. */
return INSN_CODE_SEG_PARAMS(2, 2);
sel = get_segment_selector(regs, INAT_SEG_REG_CS);
if (sel < 0)
return sel;
if (!get_desc(&desc, sel))
return -EINVAL;
/*
* The most significant byte of the Type field of the segment descriptor
* determines whether a segment contains data or code. If this is a data
* segment, return error.
*/
if (!(desc.type & BIT(3)))
return -EINVAL;
switch ((desc.l << 1) | desc.d) {
case 0: /*
* Legacy mode. CS.L=0, CS.D=0. Address and operand size are
* both 16-bit.
*/
return INSN_CODE_SEG_PARAMS(2, 2);
case 1: /*
* Legacy mode. CS.L=0, CS.D=1. Address and operand size are
* both 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 4);
case 2: /*
* IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit;
* operand size is 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 8);
case 3: /* Invalid setting. CS.L=1, CS.D=1 */
/* fall through */
default:
return -EINVAL;
}
}
| 169,609 |
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 AcceleratedSurfaceBuffersSwappedCompleted(int host_id,
int route_id,
int surface_id,
bool alive,
base::TimeTicks timebase,
base::TimeDelta interval) {
AcceleratedSurfaceBuffersSwappedCompletedForGPU(host_id, route_id,
alive, true /* presented */);
AcceleratedSurfaceBuffersSwappedCompletedForRenderer(surface_id, timebase,
interval);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void AcceleratedSurfaceBuffersSwappedCompleted(int host_id,
int route_id,
int surface_id,
uint64 surface_handle,
bool alive,
base::TimeTicks timebase,
base::TimeDelta interval) {
AcceleratedSurfaceBuffersSwappedCompletedForGPU(host_id, route_id,
alive, surface_handle);
AcceleratedSurfaceBuffersSwappedCompletedForRenderer(surface_id, timebase,
interval);
}
| 171,353 |
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 keyring_search_iterator(const void *object, void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
unsigned long kflags = key->flags;
kenter("{%d}", key->serial);
/* ignore keys not of this type */
if (key->type != ctx->index_key.type) {
kleave(" = 0 [!type]");
return 0;
}
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
ctx->result = ERR_PTR(-EKEYREVOKED);
kleave(" = %d [invrev]", ctx->skipped_ret);
goto skipped;
}
if (key->expiry && ctx->now.tv_sec >= key->expiry) {
if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
ctx->result = ERR_PTR(-EKEYEXPIRED);
kleave(" = %d [expire]", ctx->skipped_ret);
goto skipped;
}
}
/* keys that don't match */
if (!ctx->match_data.cmp(key, &ctx->match_data)) {
kleave(" = 0 [!match]");
return 0;
}
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0) {
ctx->result = ERR_PTR(-EACCES);
kleave(" = %d [!perm]", ctx->skipped_ret);
goto skipped;
}
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
/* we set a different error code if we pass a negative key */
if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
smp_rmb();
ctx->result = ERR_PTR(key->reject_error);
kleave(" = %d [neg]", ctx->skipped_ret);
goto skipped;
}
}
/* Found */
ctx->result = make_key_ref(key, ctx->possessed);
kleave(" = 1 [found]");
return 1;
skipped:
return ctx->skipped_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 keyring_search_iterator(const void *object, void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
unsigned long kflags = READ_ONCE(key->flags);
short state = READ_ONCE(key->state);
kenter("{%d}", key->serial);
/* ignore keys not of this type */
if (key->type != ctx->index_key.type) {
kleave(" = 0 [!type]");
return 0;
}
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
ctx->result = ERR_PTR(-EKEYREVOKED);
kleave(" = %d [invrev]", ctx->skipped_ret);
goto skipped;
}
if (key->expiry && ctx->now.tv_sec >= key->expiry) {
if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
ctx->result = ERR_PTR(-EKEYEXPIRED);
kleave(" = %d [expire]", ctx->skipped_ret);
goto skipped;
}
}
/* keys that don't match */
if (!ctx->match_data.cmp(key, &ctx->match_data)) {
kleave(" = 0 [!match]");
return 0;
}
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0) {
ctx->result = ERR_PTR(-EACCES);
kleave(" = %d [!perm]", ctx->skipped_ret);
goto skipped;
}
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
/* we set a different error code if we pass a negative key */
if (state < 0) {
ctx->result = ERR_PTR(state);
kleave(" = %d [neg]", ctx->skipped_ret);
goto skipped;
}
}
/* Found */
ctx->result = make_key_ref(key, ctx->possessed);
kleave(" = 1 [found]");
return 1;
skipped:
return ctx->skipped_ret;
}
| 167,703 |
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 bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask,
UINT8 app_id)
{
UINT32 i;
btif_hh_device_t *p_dev = NULL;
if (dev_handle == BTA_HH_INVALID_HANDLE) {
APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...",
__FUNCTION__, dev_handle);
return;
}
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
p_dev = &btif_hh_cb.devices[i];
if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
p_dev->dev_handle == dev_handle) {
APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
"dev_status = %d",__FUNCTION__,
p_dev->dev_status);
APPL_TRACE_WARNING("%s: bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__,
p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2],
p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]);
APPL_TRACE_WARNING("%s: attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d",
__FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
if(p_dev->fd<0) {
p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
}
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
break;
}
p_dev = NULL;
}
if (p_dev == NULL) {
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
p_dev = &btif_hh_cb.devices[i];
p_dev->dev_handle = dev_handle;
p_dev->attr_mask = attr_mask;
p_dev->sub_class = sub_class;
p_dev->app_id = app_id;
p_dev->local_vup = FALSE;
btif_hh_cb.device_num++;
p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else{
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
}
break;
}
}
}
if (p_dev == NULL) {
APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__);
return;
}
p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask,
UINT8 app_id)
{
UINT32 i;
btif_hh_device_t *p_dev = NULL;
if (dev_handle == BTA_HH_INVALID_HANDLE) {
APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...",
__FUNCTION__, dev_handle);
return;
}
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
p_dev = &btif_hh_cb.devices[i];
if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
p_dev->dev_handle == dev_handle) {
APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
"dev_status = %d",__FUNCTION__,
p_dev->dev_status);
APPL_TRACE_WARNING("%s: bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__,
p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2],
p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]);
APPL_TRACE_WARNING("%s: attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d",
__FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
if(p_dev->fd<0) {
p_dev->fd = TEMP_FAILURE_RETRY(open(dev_path, O_RDWR | O_CLOEXEC));
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
}
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
break;
}
p_dev = NULL;
}
if (p_dev == NULL) {
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
p_dev = &btif_hh_cb.devices[i];
p_dev->dev_handle = dev_handle;
p_dev->attr_mask = attr_mask;
p_dev->sub_class = sub_class;
p_dev->app_id = app_id;
p_dev->local_vup = FALSE;
btif_hh_cb.device_num++;
p_dev->fd = TEMP_FAILURE_RETRY(open(dev_path, O_RDWR | O_CLOEXEC));
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else{
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
}
break;
}
}
}
if (p_dev == NULL) {
APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__);
return;
}
p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status);
}
| 173,430 |
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 FakeBluetoothAgentManagerClient::UnregisterAgent(
const dbus::ObjectPath& agent_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "UnregisterAgent: " << agent_path.value();
if (service_provider_ != NULL) {
error_callback.Run(bluetooth_agent_manager::kErrorInvalidArguments,
"Agent still registered");
} else {
callback.Run();
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void FakeBluetoothAgentManagerClient::UnregisterAgent(
const dbus::ObjectPath& agent_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "UnregisterAgent: " << agent_path.value();
if (service_provider_ == NULL) {
error_callback.Run(bluetooth_agent_manager::kErrorDoesNotExist,
"No agent registered");
} else if (service_provider_->object_path_ != agent_path) {
error_callback.Run(bluetooth_agent_manager::kErrorDoesNotExist,
"Agent still registered");
} else {
callback.Run();
}
}
| 171,213 |
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 UpdatePolicyForEvent(const WebInputEvent* input_event,
NavigationPolicy* policy) {
if (!input_event)
return;
unsigned short button_number = 0;
if (input_event->GetType() == WebInputEvent::kMouseUp) {
const WebMouseEvent* mouse_event =
static_cast<const WebMouseEvent*>(input_event);
switch (mouse_event->button) {
case WebMouseEvent::Button::kLeft:
button_number = 0;
break;
case WebMouseEvent::Button::kMiddle:
button_number = 1;
break;
case WebMouseEvent::Button::kRight:
button_number = 2;
break;
default:
return;
}
} else if ((WebInputEvent::IsKeyboardEventType(input_event->GetType()) &&
static_cast<const WebKeyboardEvent*>(input_event)
->windows_key_code == VKEY_RETURN) ||
WebInputEvent::IsGestureEventType(input_event->GetType())) {
button_number = 0;
} else {
return;
}
bool ctrl = input_event->GetModifiers() & WebInputEvent::kControlKey;
bool shift = input_event->GetModifiers() & WebInputEvent::kShiftKey;
bool alt = input_event->GetModifiers() & WebInputEvent::kAltKey;
bool meta = input_event->GetModifiers() & WebInputEvent::kMetaKey;
NavigationPolicy user_policy = *policy;
NavigationPolicyFromMouseEvent(button_number, ctrl, shift, alt, meta,
&user_policy);
if (user_policy == kNavigationPolicyDownload &&
*policy != kNavigationPolicyIgnore)
return;
if (user_policy == kNavigationPolicyNewWindow &&
*policy == kNavigationPolicyNewPopup)
return;
*policy = user_policy;
}
Commit Message: Only allow downloading in response to real keyboard modifiers
BUG=848531
Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf
Reviewed-on: https://chromium-review.googlesource.com/1082216
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564051}
CWE ID: | void UpdatePolicyForEvent(const WebInputEvent* input_event,
NavigationPolicy* policy) {
if (!input_event)
return;
unsigned short button_number = 0;
if (input_event->GetType() == WebInputEvent::kMouseUp) {
const WebMouseEvent* mouse_event =
static_cast<const WebMouseEvent*>(input_event);
switch (mouse_event->button) {
case WebMouseEvent::Button::kLeft:
button_number = 0;
break;
case WebMouseEvent::Button::kMiddle:
button_number = 1;
break;
case WebMouseEvent::Button::kRight:
button_number = 2;
break;
default:
return;
}
} else if ((WebInputEvent::IsKeyboardEventType(input_event->GetType()) &&
static_cast<const WebKeyboardEvent*>(input_event)
->windows_key_code == VKEY_RETURN) ||
WebInputEvent::IsGestureEventType(input_event->GetType())) {
button_number = 0;
} else {
return;
}
bool ctrl = input_event->GetModifiers() & WebInputEvent::kControlKey;
bool shift = input_event->GetModifiers() & WebInputEvent::kShiftKey;
bool alt = input_event->GetModifiers() & WebInputEvent::kAltKey;
bool meta = input_event->GetModifiers() & WebInputEvent::kMetaKey;
NavigationPolicy user_policy = *policy;
NavigationPolicyFromMouseEvent(button_number, ctrl, shift, alt, meta,
&user_policy);
if (user_policy == kNavigationPolicyNewWindow &&
*policy == kNavigationPolicyNewPopup)
return;
*policy = user_policy;
}
| 173,194 |
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 RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
visual_properties_ack_pending_ = false;
viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId();
if (view_)
view_->DidNavigate();
viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId();
if (old_surface_id == new_surface_id)
return;
} else {
if (last_received_content_source_id_ >= current_content_source_id_)
return;
}
if (!new_content_rendering_timeout_)
return;
new_content_rendering_timeout_->Start(new_content_rendering_delay_);
}
Commit Message: Start rendering timer after first navigation
Currently the new content rendering timer in the browser process,
which clears an old page's contents 4 seconds after a navigation if the
new page doesn't draw in that time, is not set on the first navigation
for a top-level frame.
This is problematic because content can exist before the first
navigation, for instance if it was created by a javascript: URL.
This CL removes the code that skips the timer activation on the first
navigation.
Bug: 844881
Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584
Reviewed-on: https://chromium-review.googlesource.com/1188589
Reviewed-by: Fady Samuel <[email protected]>
Reviewed-by: ccameron <[email protected]>
Commit-Queue: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586913}
CWE ID: CWE-20 | void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
visual_properties_ack_pending_ = false;
if (view_)
view_->DidNavigate();
} else {
if (last_received_content_source_id_ >= current_content_source_id_)
return;
}
if (!new_content_rendering_timeout_)
return;
new_content_rendering_timeout_->Start(new_content_rendering_delay_);
}
| 172,654 |
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 TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state) {
EnterAnimationType animation_type =
window_state->IsSnapped() || IsTopWindow(window_state->window())
? DEFAULT
: IMMEDIATE;
if (old_state_->GetType() == window_state->GetStateType() &&
!window_state->IsNormalStateType()) {
animation_type = IMMEDIATE;
}
old_state_->set_enter_animation_type(animation_type);
std::unique_ptr<wm::WindowState::State> our_reference =
window_state->SetStateObject(std::move(old_state_));
}
Commit Message: Fix the crash after clamshell -> tablet transition in overview mode.
This CL just reverted some changes that were made in
https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In
that CL, we changed the clamshell <-> tablet transition when clamshell
split view mode is enabled, however, we should keep the old behavior
unchanged if the feature is not enabled, i.e., overview should be ended
if it's active before the transition. Otherwise, it will cause a nullptr
dereference crash since |split_view_drag_indicators_| is not created in
clamshell overview and will be used in tablet overview.
Bug: 982507
Change-Id: I238fe9472648a446cff4ab992150658c228714dd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679306}
CWE ID: CWE-362 | void TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state) {
void TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state,
bool was_in_overview) {
// Only do bounds change animation if the window was showing in overview,
// or the top window or a window showing in splitview before leaving tablet
// mode, and the window has changed its state. Otherwise, restore its bounds
// immediately.
EnterAnimationType animation_type =
was_in_overview || window_state->IsSnapped() ||
IsTopWindow(window_state->window())
? DEFAULT
: IMMEDIATE;
if (old_state_->GetType() == window_state->GetStateType() &&
!window_state->IsNormalStateType()) {
animation_type = IMMEDIATE;
}
old_state_->set_enter_animation_type(animation_type);
std::unique_ptr<wm::WindowState::State> our_reference =
window_state->SetStateObject(std::move(old_state_));
}
| 172,403 |
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: TabGroupData::TabGroupData() {
static int next_placeholder_title_number = 1;
title_ = base::ASCIIToUTF16(
"Group " + base::NumberToString(next_placeholder_title_number));
++next_placeholder_title_number;
static SkRandom rand;
stroke_color_ = rand.nextU() | 0xff000000;
}
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 | TabGroupData::TabGroupData() {
static int next_placeholder_title_number = 1;
title_ = base::ASCIIToUTF16(
"Group " + base::NumberToString(next_placeholder_title_number));
++next_placeholder_title_number;
static SkRandom rand;
color_ = rand.nextU() | 0xff000000;
}
| 172,517 |
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 WebRunnerBrowserMainParts::PreMainMessageLoopRun() {
DCHECK(!screen_);
auto platform_screen = ui::OzonePlatform::GetInstance()->CreateScreen();
if (platform_screen) {
screen_ = std::make_unique<aura::ScreenOzone>(std::move(platform_screen));
} else {
screen_ = std::make_unique<WebRunnerScreen>();
}
display::Screen::SetScreenInstance(screen_.get());
DCHECK(!browser_context_);
browser_context_ =
std::make_unique<WebRunnerBrowserContext>(GetWebContextDataDir());
fidl::InterfaceRequest<chromium::web::Context> context_request(
std::move(context_channel_));
context_impl_ = std::make_unique<ContextImpl>(browser_context_.get());
context_binding_ = std::make_unique<fidl::Binding<chromium::web::Context>>(
context_impl_.get(), std::move(context_request));
context_binding_->set_error_handler(
[this]() { std::move(quit_closure_).Run(); });
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | void WebRunnerBrowserMainParts::PreMainMessageLoopRun() {
DCHECK(!screen_);
auto platform_screen = ui::OzonePlatform::GetInstance()->CreateScreen();
if (platform_screen) {
screen_ = std::make_unique<aura::ScreenOzone>(std::move(platform_screen));
} else {
screen_ = std::make_unique<WebRunnerScreen>();
}
display::Screen::SetScreenInstance(screen_.get());
DCHECK(!browser_context_);
browser_context_ =
std::make_unique<WebRunnerBrowserContext>(GetWebContextDataDir());
context_service_ = std::make_unique<ContextImpl>(browser_context_.get());
context_binding_ = std::make_unique<fidl::Binding<chromium::web::Context>>(
context_service_.get(), fidl::InterfaceRequest<chromium::web::Context>(
std::move(context_channel_)));
// Quit the browser main loop when the Context connection is dropped.
context_binding_->set_error_handler([this]() {
DLOG(WARNING) << "Client connection to Context service dropped.";
context_service_.reset();
std::move(quit_closure_).Run();
});
}
| 172,157 |
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 ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const chromeos::InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const input_method::InputMethodDescriptor* descriptor =
input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
| 170,479 |
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 ExtensionTtsPlatformImpl::clear_error() {
error_ = std::string();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionTtsPlatformImpl::clear_error() {
| 170,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: bqarr_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
WORKSTATE state;
int32 i;
QUERYTYPE *query;
int32 commonlen;
ITEM *ptr;
NODE *tmp;
int32 pos = 0;
#ifdef BS_DEBUG
StringInfoData pbuf;
#endif
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
state.str = NULL;
/* make polish notation (postfix, but in reverse order) */
makepol(&state);
if (!state.num)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("empty query")));
commonlen = COMPUTESIZE(state.num);
query = (QUERYTYPE *) palloc(commonlen);
SET_VARSIZE(query, commonlen);
query->size = state.num;
ptr = GETQUERY(query);
for (i = state.num - 1; i >= 0; i--)
{
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
tmp = state.str->next;
pfree(state.str);
state.str = tmp;
}
pos = query->size - 1;
findoprnd(ptr, &pos);
#ifdef BS_DEBUG
initStringInfo(&pbuf);
for (i = 0; i < query->size; i++)
{
if (ptr[i].type == OPR)
appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left);
else
appendStringInfo(&pbuf, "%d ", ptr[i].val);
}
elog(DEBUG3, "POR: %s", pbuf.data);
pfree(pbuf.data);
#endif
PG_RETURN_POINTER(query);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | bqarr_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
WORKSTATE state;
int32 i;
QUERYTYPE *query;
int32 commonlen;
ITEM *ptr;
NODE *tmp;
int32 pos = 0;
#ifdef BS_DEBUG
StringInfoData pbuf;
#endif
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
state.str = NULL;
/* make polish notation (postfix, but in reverse order) */
makepol(&state);
if (!state.num)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("empty query")));
if (state.num > QUERYTYPEMAXITEMS)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of query items (%d) exceeds the maximum allowed (%d)",
state.num, (int) QUERYTYPEMAXITEMS)));
commonlen = COMPUTESIZE(state.num);
query = (QUERYTYPE *) palloc(commonlen);
SET_VARSIZE(query, commonlen);
query->size = state.num;
ptr = GETQUERY(query);
for (i = state.num - 1; i >= 0; i--)
{
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
tmp = state.str->next;
pfree(state.str);
state.str = tmp;
}
pos = query->size - 1;
findoprnd(ptr, &pos);
#ifdef BS_DEBUG
initStringInfo(&pbuf);
for (i = 0; i < query->size; i++)
{
if (ptr[i].type == OPR)
appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left);
else
appendStringInfo(&pbuf, "%d ", ptr[i].val);
}
elog(DEBUG3, "POR: %s", pbuf.data);
pfree(pbuf.data);
#endif
PG_RETURN_POINTER(query);
}
| 166,402 |
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 char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
| 167,201 |
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: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
Commit Message:
CWE ID: CWE-119 | xps_load_sfnt_name(xps_font_t *font, char *namep)
xps_load_sfnt_name(xps_font_t *font, char *namep, const int buflen)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
length = length > buflen - 1 ? buflen - 1: length;
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
| 164,785 |
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 WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
| 172,315 |
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 ExtensionTtsSpeakCompletedFunction::RunImpl() {
int request_id;
std::string error_message;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id));
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &error_message));
ExtensionTtsController::GetInstance()->OnSpeechFinished(
request_id, error_message);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ExtensionTtsSpeakCompletedFunction::RunImpl() {
bool ExtensionTtsGetVoicesFunction::RunImpl() {
result_.reset(ExtensionTtsController::GetInstance()->GetVoices(profile()));
return true;
}
| 170,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: pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
string->space = 1;
else
string->space *= 2;
if (string->space < 0)
{
g_warning ("glyph string length overflows maximum integer size, truncated");
new_len = string->space = G_MAXINT - 8;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
Commit Message: [glyphstring] Handle overflow with very long glyphstrings
CWE ID: CWE-189 | pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
{
string->space = 4;
}
else
{
const guint max_space =
MIN (G_MAXINT, G_MAXSIZE / MAX (sizeof(PangoGlyphInfo), sizeof(gint)));
guint more_space = (guint)string->space * 2;
if (more_space > max_space)
{
more_space = max_space;
if ((guint)new_len > max_space)
{
g_error ("%s: failed to allocate glyph string of length %i\n",
G_STRLOC, new_len);
}
}
string->space = more_space;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
| 165,514 |
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 PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) {
DCHECK(is_preview_);
print_preview_context_.OnPrintPreview();
if (!InitPrintSettings(print_preview_context_.frame(),
print_preview_context_.node(),
true)) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(),
print_pages_params_->params.document_cookie));
return;
}
if (!UpdatePrintSettings(settings, true)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!print_pages_params_->params.is_first_request &&
old_print_pages_params_.get() &&
PrintMsg_Print_Params_IsEqual(*old_print_pages_params_,
*print_pages_params_)) {
PrintHostMsg_DidPreviewDocument_Params preview_params;
preview_params.reuse_existing_data = true;
preview_params.data_size = 0;
preview_params.document_cookie =
print_pages_params_->params.document_cookie;
preview_params.expected_pages_count =
print_preview_context_.total_page_count();
preview_params.modifiable = print_preview_context_.IsModifiable();
preview_params.preview_request_id =
print_pages_params_->params.preview_request_id;
Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(),
preview_params));
return;
}
old_print_pages_params_.reset();
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
if (CreatePreviewDocument()) {
DidFinishPrinting(OK);
} else {
if (notify_browser_of_print_failure_)
LOG(ERROR) << "CreatePreviewDocument failed";
DidFinishPrinting(FAIL_PREVIEW);
}
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) {
DCHECK(is_preview_);
print_preview_context_.OnPrintPreview();
if (!UpdatePrintSettings(settings, true)) {
if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(), print_pages_params_->params.document_cookie));
notify_browser_of_print_failure_ = false; // Already sent.
}
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!print_pages_params_->params.is_first_request &&
old_print_pages_params_.get() &&
PrintMsg_Print_Params_IsEqual(*old_print_pages_params_,
*print_pages_params_)) {
PrintHostMsg_DidPreviewDocument_Params preview_params;
preview_params.reuse_existing_data = true;
preview_params.data_size = 0;
preview_params.document_cookie =
print_pages_params_->params.document_cookie;
preview_params.expected_pages_count =
print_preview_context_.total_page_count();
preview_params.modifiable = print_preview_context_.IsModifiable();
preview_params.preview_request_id =
print_pages_params_->params.preview_request_id;
Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(),
preview_params));
return;
}
old_print_pages_params_.reset();
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
if (CreatePreviewDocument()) {
DidFinishPrinting(OK);
} else {
if (notify_browser_of_print_failure_)
LOG(ERROR) << "CreatePreviewDocument failed";
DidFinishPrinting(FAIL_PREVIEW);
}
}
| 170,262 |
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 struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
if (dump_one_state(x, 0, &info)) {
kfree_skb(skb);
return NULL;
}
return skb;
}
Commit Message: xfrm_user: return error pointer instead of NULL
When dump_one_state() returns an error, e.g. because of a too small
buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL
instead of an error pointer. But its callers expect an error pointer
and therefore continue to operate on a NULL skbuff.
This could lead to a privilege escalation (execution of user code in
kernel context) if the attacker has CAP_NET_ADMIN and is able to map
address 0.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
| 166,112 |
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_write_finish_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
int ret;
png_debug(1, "in png_write_finish_row");
/* Next row */
png_ptr->row_number++;
/* See if we are done */
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, go to next pass */
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
if (png_ptr->transformations & PNG_INTERLACE)
{
png_ptr->pass++;
}
else
{
/* Loop until we find a non-zero width or height pass */
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->usr_width = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
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->transformations & PNG_INTERLACE)
break;
} while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
}
/* Reset the row above the image for the next pass */
if (png_ptr->pass < 7)
{
if (png_ptr->prev_row != NULL)
png_memset(png_ptr->prev_row, 0,
(png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
png_ptr->usr_bit_depth, png_ptr->width)) + 1);
return;
}
}
#endif
/* If we get here, we've just written the last row, so we need
to flush the compressor */
do
{
/* Tell the compressor we are done */
ret = deflate(&png_ptr->zstream, Z_FINISH);
/* Check for an error */
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
}
}
else if (ret != Z_STREAM_END)
{
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Write any extra space */
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
png_ptr->zstream.avail_out);
}
deflateReset(&png_ptr->zstream);
png_ptr->zstream.data_type = Z_BINARY;
}
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_write_finish_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif
int ret;
png_debug(1, "in png_write_finish_row");
/* Next row */
png_ptr->row_number++;
/* See if we are done */
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, go to next pass */
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
if (png_ptr->transformations & PNG_INTERLACE)
{
png_ptr->pass++;
}
else
{
/* Loop until we find a non-zero width or height pass */
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->usr_width = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
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->transformations & PNG_INTERLACE)
break;
} while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
}
/* Reset the row above the image for the next pass */
if (png_ptr->pass < 7)
{
if (png_ptr->prev_row != NULL)
png_memset(png_ptr->prev_row, 0,
(png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
png_ptr->usr_bit_depth, png_ptr->width)) + 1);
return;
}
}
#endif
/* If we get here, we've just written the last row, so we need
to flush the compressor */
do
{
/* Tell the compressor we are done */
ret = deflate(&png_ptr->zstream, Z_FINISH);
/* Check for an error */
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
}
}
else if (ret != Z_STREAM_END)
{
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Write any extra space */
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
png_ptr->zstream.avail_out);
}
deflateReset(&png_ptr->zstream);
png_ptr->zstream.data_type = Z_BINARY;
}
| 172,195 |
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 AppListControllerDelegateImpl::DoCreateShortcutsFlow(
Profile* profile,
const std::string& extension_id) {
DCHECK(CanDoCreateShortcutsFlow());
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
DCHECK(service);
const extensions::Extension* extension = service->GetInstalledExtension(
extension_id);
DCHECK(extension);
gfx::NativeWindow parent_window = GetAppListWindow();
if (!parent_window)
return;
OnShowChildDialog();
chrome::ShowCreateChromeAppShortcutsDialog(
parent_window, profile, extension,
base::Bind(&AppListControllerDelegateImpl::OnCloseCreateShortcutsPrompt,
base::Unretained(this)));
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | void AppListControllerDelegateImpl::DoCreateShortcutsFlow(
Profile* profile,
const std::string& extension_id) {
DCHECK(CanDoCreateShortcutsFlow());
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile);
const extensions::Extension* extension = registry->GetInstalledExtension(
extension_id);
DCHECK(extension);
gfx::NativeWindow parent_window = GetAppListWindow();
if (!parent_window)
return;
OnShowChildDialog();
chrome::ShowCreateChromeAppShortcutsDialog(
parent_window, profile, extension,
base::Bind(&AppListControllerDelegateImpl::OnCloseCreateShortcutsPrompt,
base::Unretained(this)));
}
| 171,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: static MagickBooleanType SetGrayscaleImage(Image *image)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
PixelPacket
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace);
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
ExceptionInfo
*exception;
(void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=GetPixelRed(q);
image->colormap[image->colors].green=GetPixelGreen(q);
image->colormap[image->colors].blue=GetPixelBlue(q);
image->colors++;
}
}
SetPixelIndex(indexes+x,colormap_index[intensity]);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].opacity=(unsigned short) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
IntensityCompare);
colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
sizeof(*colormap));
if (colormap == (PixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].opacity]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex(
indexes+x))]);
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/574
CWE ID: CWE-772 | static MagickBooleanType SetGrayscaleImage(Image *image)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
PixelPacket
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace);
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
ExceptionInfo
*exception;
(void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
image->colors=0;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=GetPixelRed(q);
image->colormap[image->colors].green=GetPixelGreen(q);
image->colormap[image->colors].blue=GetPixelBlue(q);
image->colors++;
}
}
SetPixelIndex(indexes+x,colormap_index[intensity]);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].opacity=(unsigned short) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
IntensityCompare);
colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
sizeof(*colormap));
if (colormap == (PixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].opacity]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex(
indexes+x))]);
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
| 167,975 |
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 burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i)
{
char * const s = b->ptr;
const int blen = (int)buffer_string_length(b);
const int used = qs < 0 ? blen : qs;
int j = i;
for (; i < used; ++i, ++j) {
s[j] = s[i];
if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') {
s[j] = '/';
i+=2;
}
}
if (qs >= 0) {
memmove(s+j, s+qs, blen - qs);
j += blen - qs;
}
buffer_string_set_length(b, j);
return qs;
}
Commit Message: [core] fix abort in http-parseopts (fixes #2945)
fix abort in server.http-parseopts with url-path-2f-decode enabled
(thx stze)
x-ref:
"Security - SIGABRT during GET request handling with url-path-2f-decode enabled"
https://redmine.lighttpd.net/issues/2945
CWE ID: CWE-190 | static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i)
{
char * const s = b->ptr;
const int blen = (int)buffer_string_length(b);
const int used = qs < 0 ? blen : qs;
int j = i;
for (; i < used; ++i, ++j) {
s[j] = s[i];
if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') {
s[j] = '/';
i+=2;
}
}
if (qs >= 0) {
const int qslen = blen - qs;
memmove(s+j, s+qs, (size_t)qslen);
qs = j;
j += qslen;
}
buffer_string_set_length(b, j);
return qs;
}
| 169,709 |
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 RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
if (external_popup_menu_ == NULL)
return;
blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItem(selected_index);
external_popup_menu_.reset();
}
Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s)
ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl.
We need to reset external_popup_menu_ before calling it.
Bug: 912211
Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc
Reviewed-on: https://chromium-review.googlesource.com/c/1381325
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618026}
CWE ID: CWE-416 | void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
if (external_popup_menu_ == NULL)
return;
blink::WebScopedUserGesture gesture(frame_);
// We need to reset |external_popup_menu_| before calling DidSelectItem(),
// which might delete |this|.
// See ExternalPopupMenuRemoveTest.RemoveFrameOnChange
std::unique_ptr<ExternalPopupMenu> popup;
popup.swap(external_popup_menu_);
popup->DidSelectItem(selected_index);
}
| 173,072 |
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 jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
bpcc->numcmpts = box->datalen;
if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_getuint8(in, &bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
bpcc->bpcs = 0;
bpcc->numcmpts = box->datalen;
if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_getuint8(in, &bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
| 168,320 |
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: MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1552
CWE ID: CWE-369 | MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=PerceptibleReciprocal(count);
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
| 169,562 |
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 DeleteSymlink(const FilePath& file_path) {
const bool deleted = HANDLE_EINTR(unlink(file_path.value().c_str())) == 0;
return deleted;
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool DeleteSymlink(const FilePath& file_path) {
| 170,873 |
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: nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev)
{
struct sk_buff *fp, *op, *head = fq->q.fragments;
int payload_len;
fq_kill(fq);
WARN_ON(head == NULL);
WARN_ON(NFCT_FRAG6_CB(head)->offset != 0);
/* Unfragmented part is taken from the first segment. */
payload_len = ((head->data - skb_network_header(head)) -
sizeof(struct ipv6hdr) + fq->q.len -
sizeof(struct frag_hdr));
if (payload_len > IPV6_MAXPLEN) {
pr_debug("payload len is too large.\n");
goto out_oversize;
}
/* Head of list must not be cloned. */
if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) {
pr_debug("skb is cloned but can't expand head");
goto out_oom;
}
/* If the first fragment is fragmented itself, we split
* it to two chunks: the first with data and paged part
* and the second, holding only fragments. */
if (skb_has_frags(head)) {
struct sk_buff *clone;
int i, plen = 0;
if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) {
pr_debug("Can't alloc skb\n");
goto out_oom;
}
clone->next = head->next;
head->next = clone;
skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
skb_frag_list_init(head);
for (i=0; i<skb_shinfo(head)->nr_frags; i++)
plen += skb_shinfo(head)->frags[i].size;
clone->len = clone->data_len = head->data_len - plen;
head->data_len -= clone->len;
head->len -= clone->len;
clone->csum = 0;
clone->ip_summed = head->ip_summed;
NFCT_FRAG6_CB(clone)->orig = NULL;
atomic_add(clone->truesize, &nf_init_frags.mem);
}
/* We have to remove fragment header from datagram and to relocate
* header in order to calculate ICV correctly. */
skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0];
memmove(head->head + sizeof(struct frag_hdr), head->head,
(head->data - head->head) - sizeof(struct frag_hdr));
head->mac_header += sizeof(struct frag_hdr);
head->network_header += sizeof(struct frag_hdr);
skb_shinfo(head)->frag_list = head->next;
skb_reset_transport_header(head);
skb_push(head, head->data - skb_network_header(head));
atomic_sub(head->truesize, &nf_init_frags.mem);
for (fp=head->next; fp; fp = fp->next) {
head->data_len += fp->len;
head->len += fp->len;
if (head->ip_summed != fp->ip_summed)
head->ip_summed = CHECKSUM_NONE;
else if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_add(head->csum, fp->csum);
head->truesize += fp->truesize;
atomic_sub(fp->truesize, &nf_init_frags.mem);
}
head->next = NULL;
head->dev = dev;
head->tstamp = fq->q.stamp;
ipv6_hdr(head)->payload_len = htons(payload_len);
/* Yes, and fold redundant checksum back. 8) */
if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_partial(skb_network_header(head),
skb_network_header_len(head),
head->csum);
fq->q.fragments = NULL;
/* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */
fp = skb_shinfo(head)->frag_list;
if (NFCT_FRAG6_CB(fp)->orig == NULL)
/* at above code, head skb is divided into two skbs. */
fp = fp->next;
op = NFCT_FRAG6_CB(head)->orig;
for (; fp; fp = fp->next) {
struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig;
op->next = orig;
op = orig;
NFCT_FRAG6_CB(fp)->orig = NULL;
}
return head;
out_oversize:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: payload len = %d\n", payload_len);
goto out_fail;
out_oom:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: no memory for reassembly\n");
out_fail:
return NULL;
}
Commit Message: netfilter: nf_conntrack_reasm: properly handle packets fragmented into a single fragment
When an ICMPV6_PKT_TOOBIG message is received with a MTU below 1280,
all further packets include a fragment header.
Unlike regular defragmentation, conntrack also needs to "reassemble"
those fragments in order to obtain a packet without the fragment
header for connection tracking. Currently nf_conntrack_reasm checks
whether a fragment has either IP6_MF set or an offset != 0, which
makes it ignore those fragments.
Remove the invalid check and make reassembly handle fragment queues
containing only a single fragment.
Reported-and-tested-by: Ulrich Weber <[email protected]>
Signed-off-by: Patrick McHardy <[email protected]>
CWE ID: | nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev)
{
struct sk_buff *fp, *op, *head = fq->q.fragments;
int payload_len;
fq_kill(fq);
WARN_ON(head == NULL);
WARN_ON(NFCT_FRAG6_CB(head)->offset != 0);
/* Unfragmented part is taken from the first segment. */
payload_len = ((head->data - skb_network_header(head)) -
sizeof(struct ipv6hdr) + fq->q.len -
sizeof(struct frag_hdr));
if (payload_len > IPV6_MAXPLEN) {
pr_debug("payload len is too large.\n");
goto out_oversize;
}
/* Head of list must not be cloned. */
if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) {
pr_debug("skb is cloned but can't expand head");
goto out_oom;
}
/* If the first fragment is fragmented itself, we split
* it to two chunks: the first with data and paged part
* and the second, holding only fragments. */
if (skb_has_frags(head)) {
struct sk_buff *clone;
int i, plen = 0;
if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) {
pr_debug("Can't alloc skb\n");
goto out_oom;
}
clone->next = head->next;
head->next = clone;
skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
skb_frag_list_init(head);
for (i=0; i<skb_shinfo(head)->nr_frags; i++)
plen += skb_shinfo(head)->frags[i].size;
clone->len = clone->data_len = head->data_len - plen;
head->data_len -= clone->len;
head->len -= clone->len;
clone->csum = 0;
clone->ip_summed = head->ip_summed;
NFCT_FRAG6_CB(clone)->orig = NULL;
atomic_add(clone->truesize, &nf_init_frags.mem);
}
/* We have to remove fragment header from datagram and to relocate
* header in order to calculate ICV correctly. */
skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0];
memmove(head->head + sizeof(struct frag_hdr), head->head,
(head->data - head->head) - sizeof(struct frag_hdr));
head->mac_header += sizeof(struct frag_hdr);
head->network_header += sizeof(struct frag_hdr);
skb_shinfo(head)->frag_list = head->next;
skb_reset_transport_header(head);
skb_push(head, head->data - skb_network_header(head));
atomic_sub(head->truesize, &nf_init_frags.mem);
for (fp=head->next; fp; fp = fp->next) {
head->data_len += fp->len;
head->len += fp->len;
if (head->ip_summed != fp->ip_summed)
head->ip_summed = CHECKSUM_NONE;
else if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_add(head->csum, fp->csum);
head->truesize += fp->truesize;
atomic_sub(fp->truesize, &nf_init_frags.mem);
}
head->next = NULL;
head->dev = dev;
head->tstamp = fq->q.stamp;
ipv6_hdr(head)->payload_len = htons(payload_len);
/* Yes, and fold redundant checksum back. 8) */
if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_partial(skb_network_header(head),
skb_network_header_len(head),
head->csum);
fq->q.fragments = NULL;
/* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */
fp = skb_shinfo(head)->frag_list;
if (fp && NFCT_FRAG6_CB(fp)->orig == NULL)
/* at above code, head skb is divided into two skbs. */
fp = fp->next;
op = NFCT_FRAG6_CB(head)->orig;
for (; fp; fp = fp->next) {
struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig;
op->next = orig;
op = orig;
NFCT_FRAG6_CB(fp)->orig = NULL;
}
return head;
out_oversize:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: payload len = %d\n", payload_len);
goto out_fail;
out_oom:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: no memory for reassembly\n");
out_fail:
return NULL;
}
| 165,591 |
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 FrameFetchContext::UpdateTimingInfoForIFrameNavigation(
ResourceTimingInfo* info) {
if (IsDetached())
return false;
if (!GetFrame()->Owner())
return false;
if (!GetFrame()->should_send_resource_timing_info_to_parent())
return false;
if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward)
return false;
return true;
}
Commit Message: Do not forward resource timing to parent frame after back-forward navigation
LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to
send timing info to parent except for the first navigation. This flag is
cleared when the first timing is sent to parent, however this does not happen
if iframe's first navigation was by back-forward navigation. For such
iframes, we shouldn't send timings to parent at all.
Bug: 876822
Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5
Reviewed-on: https://chromium-review.googlesource.com/1186215
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Kunihiko Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#585736}
CWE ID: CWE-200 | bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation(
ResourceTimingInfo* info) {
if (IsDetached())
return false;
if (!GetFrame()->Owner())
return false;
if (!GetFrame()->should_send_resource_timing_info_to_parent())
return false;
// location may have been changed after initial navigation,
if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) {
// ...and do not report subsequent navigations in the iframe too.
GetFrame()->SetShouldSendResourceTimingInfoToParent(false);
return false;
}
return true;
}
| 172,657 |
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: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *sub_name;
int len;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
RETURN_STRINGL(sub_name, len, 0);
} else {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *sub_name;
int len;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
RETURN_STRINGL(sub_name, len, 0);
} else {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
}
| 167,047 |
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 __skb_complete_tx_timestamp(struct sk_buff *skb,
struct sock *sk,
int tstype)
{
struct sock_exterr_skb *serr;
int err;
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
serr->ee.ee_info = tstype;
if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
serr->ee.ee_data = skb_shinfo(skb)->tskey;
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
serr->ee.ee_data -= sk->sk_tskey;
}
err = sock_queue_err_skb(sk, skb);
if (err)
kfree_skb(skb);
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <[email protected]>
Signed-off-by: Soheil Hassas Yeganeh <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125 | static void __skb_complete_tx_timestamp(struct sk_buff *skb,
struct sock *sk,
int tstype,
bool opt_stats)
{
struct sock_exterr_skb *serr;
int err;
BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
serr->ee.ee_info = tstype;
serr->opt_stats = opt_stats;
if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
serr->ee.ee_data = skb_shinfo(skb)->tskey;
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
serr->ee.ee_data -= sk->sk_tskey;
}
err = sock_queue_err_skb(sk, skb);
if (err)
kfree_skb(skb);
}
| 170,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: void CoordinatorImpl::RegisterClientProcess(
mojom::ClientProcessPtr client_process_ptr,
mojom::ProcessType process_type) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mojom::ClientProcess* client_process = client_process_ptr.get();
client_process_ptr.set_connection_error_handler(
base::BindOnce(&CoordinatorImpl::UnregisterClientProcess,
base::Unretained(this), client_process));
auto identity = GetClientIdentityForCurrentRequest();
auto client_info = std::make_unique<ClientInfo>(
std::move(identity), std::move(client_process_ptr), process_type);
auto iterator_and_inserted =
clients_.emplace(client_process, std::move(client_info));
DCHECK(iterator_and_inserted.second);
}
Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained
Bug: 856578
Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9
Reviewed-on: https://chromium-review.googlesource.com/1114617
Reviewed-by: Hector Dearman <[email protected]>
Commit-Queue: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#571528}
CWE ID: CWE-416 | void CoordinatorImpl::RegisterClientProcess(
mojom::ClientProcessPtr client_process_ptr,
mojom::ProcessType process_type) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mojom::ClientProcess* client_process = client_process_ptr.get();
client_process_ptr.set_connection_error_handler(
base::BindOnce(&CoordinatorImpl::UnregisterClientProcess,
weak_ptr_factory_.GetWeakPtr(), client_process));
auto identity = GetClientIdentityForCurrentRequest();
auto client_info = std::make_unique<ClientInfo>(
std::move(identity), std::move(client_process_ptr), process_type);
auto iterator_and_inserted =
clients_.emplace(client_process, std::move(client_info));
DCHECK(iterator_and_inserted.second);
}
| 173,215 |
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 udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (addr_len)
*addr_len = sizeof(struct sockaddr_in6);
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
}
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
*addr_len = sizeof(*sin6);
}
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,481 |
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 LayoutSVGViewportContainer::calculateLocalTransform()
{
if (!m_needsTransformUpdate)
return false;
m_localToParentTransform = AffineTransform::translation(m_viewport.x(), m_viewport.y()) * viewportTransform();
m_needsTransformUpdate = false;
return true;
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | bool LayoutSVGViewportContainer::calculateLocalTransform()
void LayoutSVGViewportContainer::setNeedsTransformUpdate()
{
setMayNeedPaintInvalidationSubtree();
m_needsTransformUpdate = true;
}
static std::pair<double, double> scaleReference(const AffineTransform& transform)
{
return std::make_pair(transform.xScaleSquared(), transform.yScaleSquared());
}
LayoutSVGContainer::TransformChange LayoutSVGViewportContainer::calculateLocalTransform()
{
if (!m_needsTransformUpdate)
return TransformChange::None;
std::pair<double, double> oldScale = scaleReference(m_localToParentTransform);
m_localToParentTransform = AffineTransform::translation(m_viewport.x(), m_viewport.y()) * viewportTransform();
m_needsTransformUpdate = false;
return scaleReference(m_localToParentTransform) != oldScale
? TransformChange::Full : TransformChange::ScaleInvariant;
}
| 171,667 |
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: UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile(
Profile* profile,
bool force_immediate_load,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (chromeos::ProfileHelper::IsSigninProfile(profile))
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
chromeos::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
CHECK(user);
const std::string& username = user->email();
if (user->GetType() != user_manager::USER_TYPE_REGULAR ||
BrowserPolicyConnector::IsNonEnterpriseUser(username)) {
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
}
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
UserAffiliation affiliation = connector->GetUserAffiliation(username);
const bool is_managed_user = affiliation == USER_AFFILIATION_MANAGED;
const bool is_browser_restart =
command_line->HasSwitch(chromeos::switches::kLoginUser);
const bool wait_for_initial_policy = is_managed_user && !is_browser_restart;
DeviceManagementService* device_management_service =
connector->device_management_service();
if (wait_for_initial_policy)
device_management_service->ScheduleInitialization(0);
base::FilePath profile_dir = profile->GetPath();
const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir);
const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy);
const base::FilePath token_cache_file = legacy_dir.Append(kToken);
const base::FilePath component_policy_cache_dir =
profile_dir.Append(kPolicy).Append(kComponentsDir);
const base::FilePath external_data_dir =
profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir);
base::FilePath policy_key_dir;
CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir));
scoped_ptr<UserCloudPolicyStoreChromeOS> store(
new UserCloudPolicyStoreChromeOS(
chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
chromeos::DBusThreadManager::Get()->GetSessionManagerClient(),
background_task_runner,
username, policy_key_dir, token_cache_file, policy_cache_file));
scoped_refptr<base::SequencedTaskRunner> backend_task_runner =
content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
content::BrowserThread::GetBlockingPool()->GetSequenceToken());
scoped_refptr<base::SequencedTaskRunner> io_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::IO);
scoped_ptr<CloudExternalDataManager> external_data_manager(
new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails),
backend_task_runner,
io_task_runner,
external_data_dir,
store.get()));
if (force_immediate_load)
store->LoadImmediately();
scoped_refptr<base::SequencedTaskRunner> file_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::FILE);
scoped_ptr<UserCloudPolicyManagerChromeOS> manager(
new UserCloudPolicyManagerChromeOS(
store.PassAs<CloudPolicyStore>(),
external_data_manager.Pass(),
component_policy_cache_dir,
wait_for_initial_policy,
base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds),
base::MessageLoopProxy::current(),
file_task_runner,
io_task_runner));
bool wildcard_match = false;
if (connector->IsEnterpriseManaged() &&
chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) &&
wildcard_match &&
!connector->IsNonEnterpriseUser(username)) {
manager->EnableWildcardLoginCheck(username);
}
manager->Init(
SchemaRegistryServiceFactory::GetForContext(profile)->registry());
manager->Connect(g_browser_process->local_state(),
device_management_service,
g_browser_process->system_request_context(),
affiliation);
DCHECK(managers_.find(profile) == managers_.end());
managers_[profile] = manager.get();
return manager.Pass();
}
Commit Message: Make the policy fetch for first time login blocking
The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users.
BUG=334584
Review URL: https://codereview.chromium.org/330843002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile(
Profile* profile,
bool force_immediate_load,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (chromeos::ProfileHelper::IsSigninProfile(profile))
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
chromeos::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
CHECK(user);
// Non-managed domains will be skipped by the below check
const std::string& username = user->email();
if (user->GetType() != user_manager::USER_TYPE_REGULAR ||
BrowserPolicyConnector::IsNonEnterpriseUser(username)) {
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
}
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
UserAffiliation affiliation = connector->GetUserAffiliation(username);
const bool is_affiliated_user = affiliation == USER_AFFILIATION_MANAGED;
const bool is_browser_restart =
command_line->HasSwitch(chromeos::switches::kLoginUser);
const bool wait_for_initial_policy =
!is_browser_restart &&
(chromeos::UserManager::Get()->IsCurrentUserNew() || is_affiliated_user);
const base::TimeDelta initial_policy_fetch_timeout =
chromeos::UserManager::Get()->IsCurrentUserNew()
? base::TimeDelta::Max()
: base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds);
DeviceManagementService* device_management_service =
connector->device_management_service();
if (wait_for_initial_policy)
device_management_service->ScheduleInitialization(0);
base::FilePath profile_dir = profile->GetPath();
const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir);
const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy);
const base::FilePath token_cache_file = legacy_dir.Append(kToken);
const base::FilePath component_policy_cache_dir =
profile_dir.Append(kPolicy).Append(kComponentsDir);
const base::FilePath external_data_dir =
profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir);
base::FilePath policy_key_dir;
CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir));
scoped_ptr<UserCloudPolicyStoreChromeOS> store(
new UserCloudPolicyStoreChromeOS(
chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
chromeos::DBusThreadManager::Get()->GetSessionManagerClient(),
background_task_runner,
username, policy_key_dir, token_cache_file, policy_cache_file));
scoped_refptr<base::SequencedTaskRunner> backend_task_runner =
content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
content::BrowserThread::GetBlockingPool()->GetSequenceToken());
scoped_refptr<base::SequencedTaskRunner> io_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::IO);
scoped_ptr<CloudExternalDataManager> external_data_manager(
new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails),
backend_task_runner,
io_task_runner,
external_data_dir,
store.get()));
if (force_immediate_load)
store->LoadImmediately();
scoped_refptr<base::SequencedTaskRunner> file_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::FILE);
scoped_ptr<UserCloudPolicyManagerChromeOS> manager(
new UserCloudPolicyManagerChromeOS(
store.PassAs<CloudPolicyStore>(),
external_data_manager.Pass(),
component_policy_cache_dir,
wait_for_initial_policy,
initial_policy_fetch_timeout,
base::MessageLoopProxy::current(),
file_task_runner,
io_task_runner));
bool wildcard_match = false;
if (connector->IsEnterpriseManaged() &&
chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) &&
wildcard_match &&
!connector->IsNonEnterpriseUser(username)) {
manager->EnableWildcardLoginCheck(username);
}
manager->Init(
SchemaRegistryServiceFactory::GetForContext(profile)->registry());
manager->Connect(g_browser_process->local_state(),
device_management_service,
g_browser_process->system_request_context(),
affiliation);
DCHECK(managers_.find(profile) == managers_.end());
managers_[profile] = manager.get();
return manager.Pass();
}
| 171,150 |
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 macvlan_common_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
dev->netdev_ops = &macvlan_netdev_ops;
dev->destructor = free_netdev;
dev->header_ops = &macvlan_hard_header_ops,
dev->ethtool_ops = &macvlan_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 macvlan_common_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
dev->netdev_ops = &macvlan_netdev_ops;
dev->destructor = free_netdev;
dev->header_ops = &macvlan_hard_header_ops,
dev->ethtool_ops = &macvlan_ethtool_ops;
}
| 165,729 |
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 zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
Commit Message:
CWE ID: | static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
| 164,753 |
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 SpdyProxyClientSocket::DoReadReplyComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
switch (response_.headers->response_code()) {
case 200: // OK
next_state_ = STATE_OPEN;
return OK;
case 302: // Found / Moved Temporarily
if (SanitizeProxyRedirect(&response_, request_.url)) {
redirect_has_load_timing_info_ =
spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_);
spdy_stream_->DetachDelegate();
next_state_ = STATE_DISCONNECTED;
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
} else {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
case 407: // Proxy Authentication Required
next_state_ = STATE_OPEN;
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19 | int SpdyProxyClientSocket::DoReadReplyComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
switch (response_.headers->response_code()) {
case 200: // OK
next_state_ = STATE_OPEN;
return OK;
case 302: // Found / Moved Temporarily
if (!SanitizeProxyRedirect(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
redirect_has_load_timing_info_ =
spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_);
// Note that this triggers a RST_STREAM_CANCEL.
spdy_stream_->DetachDelegate();
next_state_ = STATE_DISCONNECTED;
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
case 407: // Proxy Authentication Required
next_state_ = STATE_OPEN;
if (!SanitizeProxyAuth(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
| 172,041 |
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: cJSON *cJSON_CreateObject( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_Object;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateObject( void )
| 167,277 |
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: kg_unseal_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int *conf_state,
gss_qop_t *qop_state,
gss_iov_buffer_desc *iov,
int iov_count,
int toktype)
{
krb5_gss_ctx_id_rec *ctx;
OM_uint32 code;
ctx = (krb5_gss_ctx_id_rec *)context_handle;
if (!ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) {
code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state,
iov, iov_count, toktype);
} else {
code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state,
iov, iov_count, toktype);
}
return code;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | kg_unseal_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int *conf_state,
gss_qop_t *qop_state,
gss_iov_buffer_desc *iov,
int iov_count,
int toktype)
{
krb5_gss_ctx_id_rec *ctx;
OM_uint32 code;
ctx = (krb5_gss_ctx_id_rec *)context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) {
code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state,
iov, iov_count, toktype);
} else {
code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state,
iov, iov_count, toktype);
}
return code;
}
| 166,820 |
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 jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 4, &tmp))
return -1;
*val = tmp;
return 0;
}
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 | static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 4, &tmp))
return -1;
*val = tmp;
return 0;
}
| 168,686 |
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: check_mountpoint(const char *progname, char *mountpoint)
{
int err;
struct stat statbuf;
/* does mountpoint exist and is it a directory? */
err = stat(mountpoint, &statbuf);
if (err) {
fprintf(stderr, "%s: failed to stat %s: %s\n", progname,
mountpoint, strerror(errno));
return EX_USAGE;
}
if (!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "%s: %s is not a directory!", progname,
mountpoint);
return EX_USAGE;
}
#if CIFS_LEGACY_SETUID_CHECK
/* do extra checks on mountpoint for legacy setuid behavior */
if (!getuid() || geteuid())
return 0;
if (statbuf.st_uid != getuid()) {
fprintf(stderr, "%s: %s is not owned by user\n", progname,
mountpoint);
return EX_USAGE;
}
if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) {
fprintf(stderr, "%s: invalid permissions on %s\n", progname,
mountpoint);
return EX_USAGE;
}
#endif /* CIFS_LEGACY_SETUID_CHECK */
return 0;
}
Commit Message:
CWE ID: CWE-59 | check_mountpoint(const char *progname, char *mountpoint)
{
int err;
struct stat statbuf;
/* does mountpoint exist and is it a directory? */
err = stat(".", &statbuf);
if (err) {
fprintf(stderr, "%s: failed to stat %s: %s\n", progname,
mountpoint, strerror(errno));
return EX_USAGE;
}
if (!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "%s: %s is not a directory!", progname,
mountpoint);
return EX_USAGE;
}
#if CIFS_LEGACY_SETUID_CHECK
/* do extra checks on mountpoint for legacy setuid behavior */
if (!getuid() || geteuid())
return 0;
if (statbuf.st_uid != getuid()) {
fprintf(stderr, "%s: %s is not owned by user\n", progname,
mountpoint);
return EX_USAGE;
}
if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) {
fprintf(stderr, "%s: invalid permissions on %s\n", progname,
mountpoint);
return EX_USAGE;
}
#endif /* CIFS_LEGACY_SETUID_CHECK */
return 0;
}
| 165,168 |
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 const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(size_t) (*p++ << 24);
*quantum|=(size_t) (*p++ << 16);
*quantum|=(size_t) (*p++ << 8);
*quantum|=(size_t) (*p++ << 0);
return(p);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(unsigned int) (*p++) << 24;
*quantum|=(unsigned int) (*p++) << 16;
*quantum|=(unsigned int) (*p++) << 8;
*quantum|=(unsigned int) (*p++) << 0;
return(p);
}
| 169,947 |
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: virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent,
int start, int count) {
removed_count_++;
}
Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods.
BUG=None
TEST=None
[email protected]
Review URL: http://codereview.chromium.org/7046093
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent,
virtual void TreeNodesRemoved(TreeModel* model,
TreeModelNode* parent,
int start,
int count) OVERRIDE {
removed_count_++;
}
| 170,471 |
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 omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_INOUT OMX_PTR configData)
{
(void)hComp;
if (configData == NULL) {
DEBUG_PRINT_ERROR("ERROR: param is null");
return OMX_ErrorBadParameter;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: can't be in invalid state");
return OMX_ErrorIncorrectStateOperation;
}
switch ((int)configIndex) {
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData);
memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate));
break;
}
case OMX_IndexConfigVideoFramerate:
{
OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData);
memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate));
break;
}
case OMX_IndexConfigCommonRotate:
{
OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData);
memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation));
break;
}
case QOMX_IndexConfigVideoIntraperiod:
{
DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod");
QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData);
memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod));
break;
}
case OMX_IndexConfigVideoAVCIntraPeriod:
{
OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod");
memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod));
break;
}
case OMX_IndexConfigCommonDeinterlace:
{
OMX_VIDEO_CONFIG_DEINTERLACE *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace");
memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace));
break;
}
case OMX_IndexConfigVideoVp8ReferenceFrame:
{
OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam =
reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame");
memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame));
break;
}
case OMX_QcomIndexConfigPerfLevel:
{
OMX_U32 perflevel;
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam =
reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel");
if (!dev_get_performance_level(&perflevel)) {
DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d",
pParam->ePerfLevel);
} else {
pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel;
}
break;
}
default:
DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex);
return OMX_ErrorUnsupportedIndex;
}
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data
Check the sanity of config/param strcuture objects
passed to get/set _ config()/parameter() methods.
Bug: 27533317
Security Vulnerability in MediaServer
omx_vdec::get_config() Can lead to arbitrary write
Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809
Conflicts:
mm-core/inc/OMX_QCOMExtns.h
mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp
mm-video-v4l2/vidc/venc/src/omx_video_base.cpp
mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp
CWE ID: CWE-20 | OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_INOUT OMX_PTR configData)
{
(void)hComp;
if (configData == NULL) {
DEBUG_PRINT_ERROR("ERROR: param is null");
return OMX_ErrorBadParameter;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: can't be in invalid state");
return OMX_ErrorIncorrectStateOperation;
}
switch ((int)configIndex) {
case OMX_IndexConfigVideoBitrate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_BITRATETYPE);
OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData);
memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate));
break;
}
case OMX_IndexConfigVideoFramerate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_FRAMERATETYPE);
OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData);
memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate));
break;
}
case OMX_IndexConfigCommonRotate:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_ROTATIONTYPE);
OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData);
memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation));
break;
}
case QOMX_IndexConfigVideoIntraperiod:
{
DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod");
VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_INTRAPERIODTYPE);
QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData);
memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod));
break;
}
case OMX_IndexConfigVideoAVCIntraPeriod:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_AVCINTRAPERIOD);
OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod");
memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod));
break;
}
case OMX_IndexConfigCommonDeinterlace:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_DEINTERLACE);
OMX_VIDEO_CONFIG_DEINTERLACE *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace");
memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace));
break;
}
case OMX_IndexConfigVideoVp8ReferenceFrame:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_VP8REFERENCEFRAMETYPE);
OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam =
reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame");
memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame));
break;
}
case OMX_QcomIndexConfigPerfLevel:
{
VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL);
OMX_U32 perflevel;
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam =
reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel");
if (!dev_get_performance_level(&perflevel)) {
DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d",
pParam->ePerfLevel);
} else {
pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel;
}
break;
}
default:
DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex);
return OMX_ErrorUnsupportedIndex;
}
return OMX_ErrorNone;
}
| 173,793 |
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 br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long now = jiffies;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
hlist_add_head(&mp->mglist, &br->mglist);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto found;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = kzalloc(sizeof(*p), GFP_ATOMIC);
err = -ENOMEM;
if (unlikely(!p))
goto err;
p->addr = *group;
p->port = port;
p->next = *pp;
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
setup_timer(&p->query_timer, br_multicast_port_group_query_expired,
(unsigned long)p);
rcu_assign_pointer(*pp, p);
found:
mod_timer(&p->timer, now + br->multicast_membership_interval);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
Commit Message: bridge: Fix mglist corruption that leads to memory corruption
The list mp->mglist is used to indicate whether a multicast group
is active on the bridge interface itself as opposed to one of the
constituent interfaces in the bridge.
Unfortunately the operation that adds the mp->mglist node to the
list neglected to check whether it has already been added. This
leads to list corruption in the form of nodes pointing to itself.
Normally this would be quite obvious as it would cause an infinite
loop when walking the list. However, as this list is never actually
walked (which means that we don't really need it, I'll get rid of
it in a subsequent patch), this instead is hidden until we perform
a delete operation on the affected nodes.
As the same node may now be pointed to by more than one node, the
delete operations can then cause modification of freed memory.
This was observed in practice to cause corruption in 512-byte slabs,
most commonly leading to crashes in jbd2.
Thanks to Josef Bacik for pointing me in the right direction.
Reported-by: Ian Page Hands <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long now = jiffies;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
if (hlist_unhashed(&mp->mglist))
hlist_add_head(&mp->mglist, &br->mglist);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto found;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = kzalloc(sizeof(*p), GFP_ATOMIC);
err = -ENOMEM;
if (unlikely(!p))
goto err;
p->addr = *group;
p->port = port;
p->next = *pp;
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
setup_timer(&p->query_timer, br_multicast_port_group_query_expired,
(unsigned long)p);
rcu_assign_pointer(*pp, p);
found:
mod_timer(&p->timer, now + br->multicast_membership_interval);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
| 165,904 |
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: gs_main_finit(gs_main_instance * minst, int exit_status, int code)
{
i_ctx_t *i_ctx_p = minst->i_ctx_p;
gs_dual_memory_t dmem = {0};
int exit_code;
ref error_object;
char *tempnames;
/* NB: need to free gs_name_table
*/
/*
* Previous versions of this code closed the devices in the
* device list here. Since these devices are now prototypes,
* they cannot be opened, so they do not need to be closed;
* alloc_restore_all will close dynamically allocated devices.
*/
tempnames = gs_main_tempnames(minst);
/* by the time we get here, we *must* avoid any random redefinitions of
* operators etc, so we push systemdict onto the top of the dict stack.
* We do this in C to avoid running into any other re-defininitions in the
* Postscript world.
*/
gs_finit_push_systemdict(i_ctx_p);
/* We have to disable BGPrint before we call interp_reclaim() to prevent the
* parent rendering thread initialising for the next page, whilst we are
* removing objects it may want to access - for example, the I/O device table.
* We also have to mess with the BeginPage/EndPage procs so that we don't
* trigger a spurious extra page to be emitted.
*/
if (minst->init_done >= 2) {
gs_main_run_string(minst,
"/BGPrint /GetDeviceParam .special_op \
{{ <</BeginPage {pop} /EndPage {pop pop //false } \
/BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
.systemvar exec",
0 , &exit_code, &error_object);
}
/*
* Close the "main" device, because it may need to write out
* data before destruction. pdfwrite needs so.
*/
if (minst->init_done >= 2) {
int code = 0;
if (idmemory->reclaim != 0) {
code = interp_reclaim(&minst->i_ctx_p, avm_global);
if (code < 0) {
ref error_name;
if (tempnames)
free(tempnames);
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
}
else {
emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
}
#ifdef MEMENTO_SQUEEZE_BUILD
if (code != gs_error_VMerror ) return gs_error_Fatal;
#else
return gs_error_Fatal;
#endif
}
i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
gx_device *pdev = i_ctx_p->pgs->device;
const char * dname = pdev->dname;
if (code < 0) {
ref error_name;
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
}
else {
emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
}
}
rc_decrement(pdev, "gs_main_finit"); /* device might be freed */
if (exit_status == 0 || exit_status == gs_error_Quit)
exit_status = code;
}
/* Flush stdout and stderr */
gs_main_run_string(minst,
"(%stdout) (w) file closefile (%stderr) (w) file closefile \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
systemdict /savedinitialgstate .forceundef",
0 , &exit_code, &error_object);
}
gp_readline_finit(minst->readline_data);
i_ctx_p = minst->i_ctx_p; /* get current interp context */
if (gs_debug_c(':')) {
print_resource_usage(minst, &gs_imemory, "Final");
dmprintf1(minst->heap, "%% Exiting instance 0x%p\n", minst);
}
/* Do the equivalent of a restore "past the bottom". */
/* This will release all memory, close all open files, etc. */
if (minst->init_done >= 1) {
gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
i_plugin_holder *h = i_ctx_p->plugin_list;
dmem = *idmemory;
code = alloc_restore_all(i_ctx_p);
if (code < 0)
emprintf1(mem_raw,
"ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
code);
i_iodev_finit(&dmem);
i_plugin_finit(mem_raw, h);
}
/* clean up redirected stdout */
if (minst->heap->gs_lib_ctx->fstdout2
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {
fclose(minst->heap->gs_lib_ctx->fstdout2);
minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;
}
minst->heap->gs_lib_ctx->stdout_is_redirected = 0;
minst->heap->gs_lib_ctx->stdout_to_stderr = 0;
/* remove any temporary files, after ghostscript has closed files */
if (tempnames) {
char *p = tempnames;
while (*p) {
unlink(p);
p += strlen(p) + 1;
}
free(tempnames);
}
gs_lib_finit(exit_status, code, minst->heap);
gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
ialloc_finit(&dmem);
return exit_status;
}
Commit Message:
CWE ID: CWE-416 | gs_main_finit(gs_main_instance * minst, int exit_status, int code)
{
i_ctx_t *i_ctx_p = minst->i_ctx_p;
gs_dual_memory_t dmem = {0};
int exit_code;
ref error_object;
char *tempnames;
/* NB: need to free gs_name_table
*/
/*
* Previous versions of this code closed the devices in the
* device list here. Since these devices are now prototypes,
* they cannot be opened, so they do not need to be closed;
* alloc_restore_all will close dynamically allocated devices.
*/
tempnames = gs_main_tempnames(minst);
/* by the time we get here, we *must* avoid any random redefinitions of
* operators etc, so we push systemdict onto the top of the dict stack.
* We do this in C to avoid running into any other re-defininitions in the
* Postscript world.
*/
gs_finit_push_systemdict(i_ctx_p);
/* We have to disable BGPrint before we call interp_reclaim() to prevent the
* parent rendering thread initialising for the next page, whilst we are
* removing objects it may want to access - for example, the I/O device table.
* We also have to mess with the BeginPage/EndPage procs so that we don't
* trigger a spurious extra page to be emitted.
*/
if (minst->init_done >= 2) {
gs_main_run_string(minst,
"/BGPrint /GetDeviceParam .special_op \
{{ <</BeginPage {pop} /EndPage {pop pop //false } \
/BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
.systemvar exec",
0 , &exit_code, &error_object);
}
/*
* Close the "main" device, because it may need to write out
* data before destruction. pdfwrite needs so.
*/
if (minst->init_done >= 2) {
int code = 0;
if (idmemory->reclaim != 0) {
code = interp_reclaim(&minst->i_ctx_p, avm_global);
if (code < 0) {
ref error_name;
if (tempnames)
free(tempnames);
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
}
else {
emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
}
#ifdef MEMENTO_SQUEEZE_BUILD
if (code != gs_error_VMerror ) return gs_error_Fatal;
#else
return gs_error_Fatal;
#endif
}
i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL &&
gx_device_is_null(i_ctx_p->pgs->device)) {
/* if the job replaced the device with the nulldevice, we we need to grestore
away that device, so the block below can properly dispense
with the default device.
*/
int code = gs_grestoreall(i_ctx_p->pgs);
if (code < 0) return_error(gs_error_Fatal);
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
gx_device *pdev = i_ctx_p->pgs->device;
const char * dname = pdev->dname;
if (code < 0) {
ref error_name;
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
}
else {
emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
}
}
rc_decrement(pdev, "gs_main_finit"); /* device might be freed */
if (exit_status == 0 || exit_status == gs_error_Quit)
exit_status = code;
}
/* Flush stdout and stderr */
gs_main_run_string(minst,
"(%stdout) (w) file closefile (%stderr) (w) file closefile \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
systemdict /savedinitialgstate .forceundef",
0 , &exit_code, &error_object);
}
gp_readline_finit(minst->readline_data);
i_ctx_p = minst->i_ctx_p; /* get current interp context */
if (gs_debug_c(':')) {
print_resource_usage(minst, &gs_imemory, "Final");
dmprintf1(minst->heap, "%% Exiting instance 0x%p\n", minst);
}
/* Do the equivalent of a restore "past the bottom". */
/* This will release all memory, close all open files, etc. */
if (minst->init_done >= 1) {
gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
i_plugin_holder *h = i_ctx_p->plugin_list;
dmem = *idmemory;
code = alloc_restore_all(i_ctx_p);
if (code < 0)
emprintf1(mem_raw,
"ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
code);
i_iodev_finit(&dmem);
i_plugin_finit(mem_raw, h);
}
/* clean up redirected stdout */
if (minst->heap->gs_lib_ctx->fstdout2
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {
fclose(minst->heap->gs_lib_ctx->fstdout2);
minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;
}
minst->heap->gs_lib_ctx->stdout_is_redirected = 0;
minst->heap->gs_lib_ctx->stdout_to_stderr = 0;
/* remove any temporary files, after ghostscript has closed files */
if (tempnames) {
char *p = tempnames;
while (*p) {
unlink(p);
p += strlen(p) + 1;
}
free(tempnames);
}
gs_lib_finit(exit_status, code, minst->heap);
gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
ialloc_finit(&dmem);
return exit_status;
}
| 164,695 |
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 CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Z_Malloc = Z_Malloc;
ri.Free = Z_Free;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
Cvar_Set( "cl_paused", "0" );
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269 | void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Z_Malloc = Z_Malloc;
ri.Free = Z_Free;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
Cvar_Set( "cl_paused", "0" );
}
| 170,086 |
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: kvp_respond_to_host(char *key, char *value, int error)
{
struct hv_kvp_msg *kvp_msg;
struct hv_kvp_msg_enumerate *kvp_data;
char *key_name;
struct icmsg_hdr *icmsghdrp;
int keylen, valuelen;
u32 buf_len;
struct vmbus_channel *channel;
u64 req_id;
/*
* If a transaction is not active; log and return.
*/
if (!kvp_transaction.active) {
/*
* This is a spurious call!
*/
pr_warn("KVP: Transaction not active\n");
return;
}
/*
* Copy the global state for completing the transaction. Note that
* only one transaction can be active at a time.
*/
buf_len = kvp_transaction.recv_len;
channel = kvp_transaction.recv_channel;
req_id = kvp_transaction.recv_req_id;
kvp_transaction.active = false;
if (channel->onchannel_callback == NULL)
/*
* We have raced with util driver being unloaded;
* silently return.
*/
return;
icmsghdrp = (struct icmsg_hdr *)
&recv_buffer[sizeof(struct vmbuspipe_hdr)];
kvp_msg = (struct hv_kvp_msg *)
&recv_buffer[sizeof(struct vmbuspipe_hdr) +
sizeof(struct icmsg_hdr)];
kvp_data = &kvp_msg->kvp_data;
key_name = key;
/*
* If the error parameter is set, terminate the host's enumeration.
*/
if (error) {
/*
* We don't support this index or the we have timedout;
* terminate the host-side iteration by returning an error.
*/
icmsghdrp->status = HV_E_FAIL;
goto response_done;
}
/*
* The windows host expects the key/value pair to be encoded
* in utf16.
*/
keylen = utf8s_to_utf16s(key_name, strlen(key_name),
(wchar_t *)kvp_data->data.key);
kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */
valuelen = utf8s_to_utf16s(value, strlen(value),
(wchar_t *)kvp_data->data.value);
kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */
kvp_data->data.value_type = REG_SZ; /* all our values are strings */
icmsghdrp->status = HV_S_OK;
response_done:
icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;
vmbus_sendpacket(channel, recv_buffer, buf_len, req_id,
VM_PKT_DATA_INBAND, 0);
}
Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine
The utf8s_to_utf16s conversion routine needs to be improved. Unlike
its utf16s_to_utf8s sibling, it doesn't accept arguments specifying
the maximum length of the output buffer or the endianness of its
16-bit output.
This patch (as1501) adds the two missing arguments, and adjusts the
only two places in the kernel where the function is called. A
follow-on patch will add a third caller that does utilize the new
capabilities.
The two conversion routines are still annoyingly inconsistent in the
way they handle invalid byte combinations. But that's a subject for a
different patch.
Signed-off-by: Alan Stern <[email protected]>
CC: Clemens Ladisch <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | kvp_respond_to_host(char *key, char *value, int error)
{
struct hv_kvp_msg *kvp_msg;
struct hv_kvp_msg_enumerate *kvp_data;
char *key_name;
struct icmsg_hdr *icmsghdrp;
int keylen, valuelen;
u32 buf_len;
struct vmbus_channel *channel;
u64 req_id;
/*
* If a transaction is not active; log and return.
*/
if (!kvp_transaction.active) {
/*
* This is a spurious call!
*/
pr_warn("KVP: Transaction not active\n");
return;
}
/*
* Copy the global state for completing the transaction. Note that
* only one transaction can be active at a time.
*/
buf_len = kvp_transaction.recv_len;
channel = kvp_transaction.recv_channel;
req_id = kvp_transaction.recv_req_id;
kvp_transaction.active = false;
if (channel->onchannel_callback == NULL)
/*
* We have raced with util driver being unloaded;
* silently return.
*/
return;
icmsghdrp = (struct icmsg_hdr *)
&recv_buffer[sizeof(struct vmbuspipe_hdr)];
kvp_msg = (struct hv_kvp_msg *)
&recv_buffer[sizeof(struct vmbuspipe_hdr) +
sizeof(struct icmsg_hdr)];
kvp_data = &kvp_msg->kvp_data;
key_name = key;
/*
* If the error parameter is set, terminate the host's enumeration.
*/
if (error) {
/*
* We don't support this index or the we have timedout;
* terminate the host-side iteration by returning an error.
*/
icmsghdrp->status = HV_E_FAIL;
goto response_done;
}
/*
* The windows host expects the key/value pair to be encoded
* in utf16.
*/
keylen = utf8s_to_utf16s(key_name, strlen(key_name), UTF16_HOST_ENDIAN,
(wchar_t *) kvp_data->data.key,
HV_KVP_EXCHANGE_MAX_KEY_SIZE / 2);
kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */
valuelen = utf8s_to_utf16s(value, strlen(value), UTF16_HOST_ENDIAN,
(wchar_t *) kvp_data->data.value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2);
kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */
kvp_data->data.value_type = REG_SZ; /* all our values are strings */
icmsghdrp->status = HV_S_OK;
response_done:
icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;
vmbus_sendpacket(channel, recv_buffer, buf_len, req_id,
VM_PKT_DATA_INBAND, 0);
}
| 166,123 |
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 *ReadGRAYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*canvas_image,
*image;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
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);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(size_t) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
Create virtual canvas to support cropping (i.e. image.gray[100x100+10+20]).
*/
SetImageColorspace(image,GRAYColorspace);
canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,
exception);
(void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,canvas_image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if (image_info->number_scenes != 0)
while (image->scene < image_info->scene)
{
/*
Skip to next image.
*/
image->scene++;
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
}
scene=0;
count=0;
length=0;
do
{
/*
Read pixels to virtual canvas image then push to image.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
SetImageColorspace(image,GRAYColorspace);
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
x;
register PixelPacket
*restrict q;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
image->columns,1,exception);
q=QueueAuthenticPixels(image,0,y-image->extract_info.y,image->columns,
1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
SetQuantumImageType(image,quantum_type);
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (count == (ssize_t) length)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
scene++;
} while (count == (ssize_t) length);
quantum_info=DestroyQuantumInfo(quantum_info);
InheritException(&image->exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadGRAYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*canvas_image,
*image;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
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);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(size_t) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
Create virtual canvas to support cropping (i.e. image.gray[100x100+10+20]).
*/
SetImageColorspace(image,GRAYColorspace);
canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,
exception);
(void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,canvas_image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if (image_info->number_scenes != 0)
while (image->scene < image_info->scene)
{
/*
Skip to next image.
*/
image->scene++;
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
}
scene=0;
count=0;
length=0;
do
{
/*
Read pixels to virtual canvas image then push to image.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
SetImageColorspace(image,GRAYColorspace);
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
x;
register PixelPacket
*restrict q;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
image->columns,1,exception);
q=QueueAuthenticPixels(image,0,y-image->extract_info.y,image->columns,
1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
SetQuantumImageType(image,quantum_type);
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (count == (ssize_t) length)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
scene++;
} while (count == (ssize_t) length);
quantum_info=DestroyQuantumInfo(quantum_info);
InheritException(&image->exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,568 |
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: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
Commit Message: Fix always true condition (Thomas Jarosch)
CWE ID: CWE-119 | do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
| 167,628 |
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: process(register int code, unsigned char** fill)
{
int incode;
static unsigned char firstchar;
if (code == clear) {
codesize = datasize + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
return 1;
}
if (oldcode == -1) {
*(*fill)++ = suffix[code];
firstchar = oldcode = code;
return 1;
}
if (code > avail) {
fprintf(stderr, "code %d too large for %d\n", code, avail);
return 0;
}
incode = code;
if (code == avail) { /* the first code is always < avail */
*stackp++ = firstchar;
code = oldcode;
}
while (code > clear) {
*stackp++ = suffix[code];
code = prefix[code];
}
*stackp++ = firstchar = suffix[code];
prefix[avail] = oldcode;
suffix[avail] = firstchar;
avail++;
if (((avail & codemask) == 0) && (avail < 4096)) {
codesize++;
codemask += avail;
}
oldcode = incode;
do {
*(*fill)++ = *--stackp;
} while (stackp > stack);
return 1;
}
Commit Message: fix possible OOB write in gif2tiff.c
CWE ID: CWE-119 | process(register int code, unsigned char** fill)
{
int incode;
static unsigned char firstchar;
if (code == clear) {
codesize = datasize + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
return 1;
}
if (oldcode == -1) {
if (code >= clear) {
fprintf(stderr, "bad input: code=%d is larger than clear=%d\n",code, clear);
return 0;
}
*(*fill)++ = suffix[code];
firstchar = oldcode = code;
return 1;
}
if (code > avail) {
fprintf(stderr, "code %d too large for %d\n", code, avail);
return 0;
}
incode = code;
if (code == avail) { /* the first code is always < avail */
*stackp++ = firstchar;
code = oldcode;
}
while (code > clear) {
*stackp++ = suffix[code];
code = prefix[code];
}
*stackp++ = firstchar = suffix[code];
prefix[avail] = oldcode;
suffix[avail] = firstchar;
avail++;
if (((avail & codemask) == 0) && (avail < 4096)) {
codesize++;
codemask += avail;
}
oldcode = incode;
do {
*(*fill)++ = *--stackp;
} while (stackp > stack);
return 1;
}
| 166,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
if (unix_sock_count) {
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
}
return max_level;
}
Commit Message: unix: properly account for FDs passed over unix sockets
It is possible for a process to allocate and accumulate far more FDs than
the process' limit by sending them over a unix socket then closing them
to keep the process' fd count low.
This change addresses this problem by keeping track of the number of FDs
in flight per user and preventing non-privileged processes from having
more FDs in flight than their configured FD limit.
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
if (too_many_unix_fds(current))
return -ETOOMANYREFS;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
return max_level;
}
| 167,596 |
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: rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
ND_TCHECK(opt->rpl_dio_len);
}
return;
trunc:
ND_PRINT((ndo, "%s", rpl_tstr));
return;
}
| 169,831 |
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 rd_release_device_space(struct rd_dev *rd_dev)
{
u32 i, j, page_count = 0, sg_per_table;
struct rd_dev_sg_table *sg_table;
struct page *pg;
struct scatterlist *sg;
if (!rd_dev->sg_table_array || !rd_dev->sg_table_count)
return;
sg_table = rd_dev->sg_table_array;
for (i = 0; i < rd_dev->sg_table_count; i++) {
sg = sg_table[i].sg_table;
sg_per_table = sg_table[i].rd_sg_count;
for (j = 0; j < sg_per_table; j++) {
pg = sg_page(&sg[j]);
if (pg) {
__free_page(pg);
page_count++;
}
}
kfree(sg);
}
pr_debug("CORE_RD[%u] - Released device space for Ramdisk"
" Device ID: %u, pages %u in %u tables total bytes %lu\n",
rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,
rd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);
kfree(sg_table);
rd_dev->sg_table_array = NULL;
rd_dev->sg_table_count = 0;
}
Commit Message: target/rd: Refactor rd_build_device_space + rd_release_device_space
This patch refactors rd_build_device_space() + rd_release_device_space()
into rd_allocate_sgl_table() + rd_release_device_space() so that they
may be used seperatly for setup + release of protection information
scatterlists.
Also add explicit memset of pages within rd_allocate_sgl_table() based
upon passed 'init_payload' value.
v2 changes:
- Drop unused sg_table from rd_release_device_space (Wei)
Cc: Martin K. Petersen <[email protected]>
Cc: Christoph Hellwig <[email protected]>
Cc: Hannes Reinecke <[email protected]>
Cc: Sagi Grimberg <[email protected]>
Cc: Or Gerlitz <[email protected]>
Signed-off-by: Nicholas Bellinger <[email protected]>
CWE ID: CWE-264 | static void rd_release_device_space(struct rd_dev *rd_dev)
static u32 rd_release_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table,
u32 sg_table_count)
{
struct page *pg;
struct scatterlist *sg;
u32 i, j, page_count = 0, sg_per_table;
for (i = 0; i < sg_table_count; i++) {
sg = sg_table[i].sg_table;
sg_per_table = sg_table[i].rd_sg_count;
for (j = 0; j < sg_per_table; j++) {
pg = sg_page(&sg[j]);
if (pg) {
__free_page(pg);
page_count++;
}
}
kfree(sg);
}
kfree(sg_table);
return page_count;
}
static void rd_release_device_space(struct rd_dev *rd_dev)
{
u32 page_count;
if (!rd_dev->sg_table_array || !rd_dev->sg_table_count)
return;
page_count = rd_release_sgl_table(rd_dev, rd_dev->sg_table_array,
rd_dev->sg_table_count);
pr_debug("CORE_RD[%u] - Released device space for Ramdisk"
" Device ID: %u, pages %u in %u tables total bytes %lu\n",
rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,
rd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);
rd_dev->sg_table_array = NULL;
rd_dev->sg_table_count = 0;
}
| 166,316 |
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 PrintRenderFrameHelper::PrintHeaderAndFooter(
blink::WebCanvas* canvas,
int page_number,
int total_pages,
const blink::WebLocalFrame& source_frame,
float webkit_scale_factor,
const PageSizeMargins& page_layout,
const PrintMsg_Print_Params& params) {
cc::PaintCanvasAutoRestore auto_restore(canvas, true);
canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
page_layout.content_width,
page_layout.margin_top + page_layout.margin_bottom +
page_layout.content_height);
blink::WebView* web_view = blink::WebView::Create(
nullptr, blink::mojom::PageVisibilityState::kVisible);
web_view->GetSettings()->SetJavaScriptEnabled(true);
class HeaderAndFooterClient final : public blink::WebFrameClient {
public:
void BindToFrame(blink::WebLocalFrame* frame) override { frame_ = frame; }
void FrameDetached(DetachType detach_type) override {
frame_->FrameWidget()->Close();
frame_->Close();
frame_ = nullptr;
}
private:
blink::WebLocalFrame* frame_;
};
HeaderAndFooterClient frame_client;
blink::WebLocalFrame* frame = blink::WebLocalFrame::CreateMainFrame(
web_view, &frame_client, nullptr, nullptr);
blink::WebWidgetClient web_widget_client;
blink::WebFrameWidget::Create(&web_widget_client, frame);
base::Value html(base::UTF8ToUTF16(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_PRINT_PREVIEW_PAGE)));
ExecuteScript(frame, kPageLoadScriptFormat, html);
auto options = base::MakeUnique<base::DictionaryValue>();
options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
options->SetDouble("width", page_size.width);
options->SetDouble("height", page_size.height);
options->SetDouble("topMargin", page_layout.margin_top);
options->SetDouble("bottomMargin", page_layout.margin_bottom);
options->SetInteger("pageNumber", page_number);
options->SetInteger("totalPages", total_pages);
options->SetString("url", params.url);
base::string16 title = source_frame.GetDocument().Title().Utf16();
options->SetString("title", title.empty() ? params.title : title);
ExecuteScript(frame, kPageSetupScriptFormat, *options);
blink::WebPrintParams webkit_params(page_size);
webkit_params.printer_dpi = GetDPI(¶ms);
frame->PrintBegin(webkit_params);
frame->PrintPage(0, canvas);
frame->PrintEnd();
web_view->Close();
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Jianzhou Feng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20 | void PrintRenderFrameHelper::PrintHeaderAndFooter(
blink::WebCanvas* canvas,
int page_number,
int total_pages,
const blink::WebLocalFrame& source_frame,
float webkit_scale_factor,
const PageSizeMargins& page_layout,
const PrintMsg_Print_Params& params) {
cc::PaintCanvasAutoRestore auto_restore(canvas, true);
canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
page_layout.content_width,
page_layout.margin_top + page_layout.margin_bottom +
page_layout.content_height);
blink::WebView* web_view = blink::WebView::Create(
nullptr, blink::mojom::PageVisibilityState::kVisible);
web_view->GetSettings()->SetJavaScriptEnabled(true);
class HeaderAndFooterClient final : public blink::WebFrameClient {
public:
void BindToFrame(blink::WebLocalFrame* frame) override { frame_ = frame; }
void FrameDetached(DetachType detach_type) override {
frame_->FrameWidget()->Close();
frame_->Close();
frame_ = nullptr;
}
private:
blink::WebLocalFrame* frame_;
};
HeaderAndFooterClient frame_client;
blink::WebLocalFrame* frame = blink::WebLocalFrame::CreateMainFrame(
web_view, &frame_client, nullptr, nullptr);
blink::WebWidgetClient web_widget_client;
blink::WebFrameWidget::Create(&web_widget_client, frame);
base::Value html(base::UTF8ToUTF16(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_PRINT_PREVIEW_PAGE)));
ExecuteScript(frame, kPageLoadScriptFormat, html);
auto options = base::MakeUnique<base::DictionaryValue>();
options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
options->SetDouble("width", page_size.width);
options->SetDouble("height", page_size.height);
options->SetDouble("topMargin", page_layout.margin_top);
options->SetDouble("bottomMargin", page_layout.margin_bottom);
options->SetInteger("pageNumber", page_number);
options->SetInteger("totalPages", total_pages);
options->SetString("url", params.url);
base::string16 title = source_frame.GetDocument().Title().Utf16();
options->SetString("title", title.empty() ? params.title : title);
options->SetString("headerTemplate", params.header_template);
options->SetString("footerTemplate", params.footer_template);
ExecuteScript(frame, kPageSetupScriptFormat, *options);
blink::WebPrintParams webkit_params(page_size);
webkit_params.printer_dpi = GetDPI(¶ms);
frame->PrintBegin(webkit_params);
frame->PrintPage(0, canvas);
frame->PrintEnd();
web_view->Close();
}
| 172,899 |
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 HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
rules_.ParseFromString(server_whitelist);
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | void HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
// TODO(eroman): Is this necessary? The issue is that
// HttpAuthFilterWhitelist is trying to use ProxyBypassRules as a generic
// URL filter. However internally it has some implicit rules for localhost
// and linklocal addresses.
rules_.ParseFromString(ProxyBypassRules::GetRulesToSubtractImplicit() + ";" +
server_whitelist);
}
| 172,644 |
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 SeekHead::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
int entry_count = 0;
int void_element_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) // SeekEntry ID
++entry_count;
else if (id == 0x6C) // Void ID
++void_element_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
m_entries = new (std::nothrow) Entry[entry_count];
if (m_entries == NULL)
return -1;
m_void_elements = new (std::nothrow) VoidElement[void_element_count];
if (m_void_elements == NULL)
return -1;
Entry* pEntry = m_entries;
VoidElement* pVoidElement = m_void_elements;
pos = m_start;
while (pos < stop) {
const long long idpos = pos;
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) { // SeekEntry ID
if (ParseEntry(pReader, pos, size, pEntry)) {
Entry& e = *pEntry++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
} else if (id == 0x6C) { // Void ID
VoidElement& e = *pVoidElement++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
assert(count_ >= 0);
assert(count_ <= entry_count);
m_entry_count = static_cast<int>(count_);
count_ = ptrdiff_t(pVoidElement - m_void_elements);
assert(count_ >= 0);
assert(count_ <= void_element_count);
m_void_element_count = static_cast<int>(count_);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long SeekHead::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
int entry_count = 0;
int void_element_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) // SeekEntry ID
++entry_count;
else if (id == 0x6C) // Void ID
++void_element_count;
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
m_entries = new (std::nothrow) Entry[entry_count];
if (m_entries == NULL)
return -1;
m_void_elements = new (std::nothrow) VoidElement[void_element_count];
if (m_void_elements == NULL)
return -1;
Entry* pEntry = m_entries;
VoidElement* pVoidElement = m_void_elements;
pos = m_start;
while (pos < stop) {
const long long idpos = pos;
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) { // SeekEntry ID
if (ParseEntry(pReader, pos, size, pEntry)) {
Entry& e = *pEntry++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
} else if (id == 0x6C) { // Void ID
VoidElement& e = *pVoidElement++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
assert(count_ >= 0);
assert(count_ <= entry_count);
m_entry_count = static_cast<int>(count_);
count_ = ptrdiff_t(pVoidElement - m_void_elements);
assert(count_ >= 0);
assert(count_ <= void_element_count);
m_void_element_count = static_cast<int>(count_);
return 0;
}
| 173,836 |
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: getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
static getprivs_ret ret;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_getprivs_ret, &ret);
if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
ret.code = kadm5_get_privs((void *)handle, &ret.privs);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_privs", client_name.value, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
static getprivs_ret ret;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_getprivs_ret, &ret);
if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
ret.code = kadm5_get_privs((void *)handle, &ret.privs);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_privs", client_name.value, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,517 |
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 gatherSecurityPolicyViolationEventData(
SecurityPolicyViolationEventInit& init,
ExecutionContext* context,
const String& directiveText,
const ContentSecurityPolicy::DirectiveType& effectiveType,
const KURL& blockedURL,
const String& header,
RedirectStatus redirectStatus,
ContentSecurityPolicyHeaderType headerType,
ContentSecurityPolicy::ViolationType violationType,
int contextLine,
const String& scriptSource) {
if (effectiveType == ContentSecurityPolicy::DirectiveType::FrameAncestors) {
init.setDocumentURI(blockedURL.getString());
init.setBlockedURI(blockedURL.getString());
} else {
init.setDocumentURI(context->url().getString());
switch (violationType) {
case ContentSecurityPolicy::InlineViolation:
init.setBlockedURI("inline");
break;
case ContentSecurityPolicy::EvalViolation:
init.setBlockedURI("eval");
break;
case ContentSecurityPolicy::URLViolation:
init.setBlockedURI(stripURLForUseInReport(
context, blockedURL, redirectStatus, effectiveType));
break;
}
}
String effectiveDirective =
ContentSecurityPolicy::getDirectiveName(effectiveType);
init.setViolatedDirective(effectiveDirective);
init.setEffectiveDirective(effectiveDirective);
init.setOriginalPolicy(header);
init.setDisposition(headerType == ContentSecurityPolicyHeaderTypeEnforce
? "enforce"
: "report");
init.setSourceFile(String());
init.setLineNumber(contextLine);
init.setColumnNumber(0);
init.setStatusCode(0);
if (context->isDocument()) {
Document* document = toDocument(context);
DCHECK(document);
init.setReferrer(document->referrer());
if (!SecurityOrigin::isSecure(context->url()) && document->loader())
init.setStatusCode(document->loader()->response().httpStatusCode());
}
std::unique_ptr<SourceLocation> location = SourceLocation::capture(context);
if (location->lineNumber()) {
KURL source = KURL(ParsedURLString, location->url());
init.setSourceFile(
stripURLForUseInReport(context, source, redirectStatus, effectiveType));
init.setLineNumber(location->lineNumber());
init.setColumnNumber(location->columnNumber());
}
if (!scriptSource.isEmpty())
init.setSample(scriptSource.stripWhiteSpace().left(40));
}
Commit Message: CSP: Strip the fragment from reported URLs.
We should have been stripping the fragment from the URL we report for
CSP violations, but we weren't. Now we are, by running the URLs through
`stripURLForUseInReport()`, which implements the stripping algorithm
from CSP2: https://www.w3.org/TR/CSP2/#strip-uri-for-reporting
Eventually, we will migrate more completely to the CSP3 world that
doesn't require such detailed stripping, as it exposes less data to the
reports, but we're not there yet.
BUG=678776
Review-Url: https://codereview.chromium.org/2619783002
Cr-Commit-Position: refs/heads/master@{#458045}
CWE ID: CWE-200 | static void gatherSecurityPolicyViolationEventData(
SecurityPolicyViolationEventInit& init,
ExecutionContext* context,
const String& directiveText,
const ContentSecurityPolicy::DirectiveType& effectiveType,
const KURL& blockedURL,
const String& header,
RedirectStatus redirectStatus,
ContentSecurityPolicyHeaderType headerType,
ContentSecurityPolicy::ViolationType violationType,
int contextLine,
const String& scriptSource) {
if (effectiveType == ContentSecurityPolicy::DirectiveType::FrameAncestors) {
String strippedURL = stripURLForUseInReport(
context, blockedURL, RedirectStatus::NoRedirect,
ContentSecurityPolicy::DirectiveType::DefaultSrc);
init.setDocumentURI(strippedURL);
init.setBlockedURI(strippedURL);
} else {
String strippedURL = stripURLForUseInReport(
context, context->url(), RedirectStatus::NoRedirect,
ContentSecurityPolicy::DirectiveType::DefaultSrc);
init.setDocumentURI(strippedURL);
switch (violationType) {
case ContentSecurityPolicy::InlineViolation:
init.setBlockedURI("inline");
break;
case ContentSecurityPolicy::EvalViolation:
init.setBlockedURI("eval");
break;
case ContentSecurityPolicy::URLViolation:
init.setBlockedURI(stripURLForUseInReport(
context, blockedURL, redirectStatus, effectiveType));
break;
}
}
String effectiveDirective =
ContentSecurityPolicy::getDirectiveName(effectiveType);
init.setViolatedDirective(effectiveDirective);
init.setEffectiveDirective(effectiveDirective);
init.setOriginalPolicy(header);
init.setDisposition(headerType == ContentSecurityPolicyHeaderTypeEnforce
? "enforce"
: "report");
init.setSourceFile(String());
init.setLineNumber(contextLine);
init.setColumnNumber(0);
init.setStatusCode(0);
if (context->isDocument()) {
Document* document = toDocument(context);
DCHECK(document);
init.setReferrer(document->referrer());
if (!SecurityOrigin::isSecure(context->url()) && document->loader())
init.setStatusCode(document->loader()->response().httpStatusCode());
}
std::unique_ptr<SourceLocation> location = SourceLocation::capture(context);
if (location->lineNumber()) {
KURL source = KURL(ParsedURLString, location->url());
init.setSourceFile(
stripURLForUseInReport(context, source, redirectStatus, effectiveType));
init.setLineNumber(location->lineNumber());
init.setColumnNumber(location->columnNumber());
}
if (!scriptSource.isEmpty())
init.setSample(scriptSource.stripWhiteSpace().left(40));
}
| 172,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: gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
Commit Message:
CWE ID: CWE-119 | gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
*session_data_size = psession.size;
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
| 164,570 |
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 UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
| 169,290 |
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)
{
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = kiocb->ki_left;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
static ssize_t aio_setup_single_vector(int type, struct file * file, struct kiocb *kiocb)
{
int bytes;
bytes = rw_verify_area(type, file, &kiocb->ki_pos, kiocb->ki_left);
if (bytes < 0)
return bytes;
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = bytes;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
| 167,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 AppCacheDatabase::FindEntriesForUrl(
const GURL& url, std::vector<EntryRecord>* records) {
DCHECK(records && records->empty());
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, url, flags, response_id, response_size FROM Entries"
" WHERE url = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, url.spec());
while (statement.Step()) {
records->push_back(EntryRecord());
ReadEntryRecord(statement, &records->back());
DCHECK(records->back().url == url);
}
return statement.Succeeded();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | bool AppCacheDatabase::FindEntriesForUrl(
const GURL& url, std::vector<EntryRecord>* records) {
DCHECK(records && records->empty());
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, url, flags, response_id, response_size, padding_size "
"FROM Entries"
" WHERE url = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, url.spec());
while (statement.Step()) {
records->push_back(EntryRecord());
ReadEntryRecord(statement, &records->back());
DCHECK(records->back().url == url);
}
return statement.Succeeded();
}
| 172,976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.